How to use double colon:: in Kotlin

  • 2021-11-13 02:35:12
  • OfStack

The double colon operator in Kotlin indicates that a method is used as a parameter and passed to another method for use. Generally speaking, it refers to a method. Let's look at an example first:


fun main(args: Array<String>) {
 println(lock("param1", "param2", ::getResult))
}

/**
 * @param str1  Parameter 1
 * @param str2  Parameter 2
 */
fun getResult(str1: String, str2: String): String = "result is {$str1 , $str2}"

/**
 * @param p1  Parameter 1
 * @param p2  Parameter 2
 * @param method  Method name 
 */
fun lock(p1: String, p2: String, method: (str1: String, str2: String) -> String): String {
 return method(p1, p2)
}

It should be noted here that when the third parameter of lock function is passed into method, it is necessary to determine that the number, type and return value of the parameters are consistent with its formal parameter 1.

Output:

result is {param1 , param2}

If we need to call one of the other methods in Class:

It is written as:


fun main(args: Array<String>) {
 var d = Test()
 println(lock("param1", "param2", d::getResult))
}

When we use a double colon in a method in Class to call the internal method of the current Class, the transfer mode is as follows:


class Test1 {
 fun isOdd(x: Int) = x % 2 != 0

 fun test() {
  var list = listOf(1, 2, 3, 4, 5)
  println(list.filter(this::isOdd))
 }
}

In general, the method this that we call the current class can be omitted. The reason why it cannot be omitted here is

To prevent scope confusion, if the function called by:: is a member function of a class or an extension function, it must use qualifiers, such as this

If isOdd is written outside class (global), the qualifier can also be omitted here.

Summarize


Related articles: