Double colon in kotlin: Usage

The double colon operator in kotlin means to pass a method as a parameter to another method for use. Generally speaking, it refers to a method. Let's take a look at an example:

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

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

/**
 * @param p1 参数1
 * @param p2 参数2
 * @param method 方法名称
 */
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 the lock function is passed into the method, make sure that the number, type and return value of the parameters are consistent with their formal parameters.

Output results:

If we need to call a method in another class:

Written as:

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

When we call the internal method of the current class with a double colon in a method of the class, the transfer method is:

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, we can omit this when calling the method of the current class. The reason why we can't omit here is

If you write Isodd outside the class (global), you can also omit the qualifier here.

summary

The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. Thank you for your support.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>