What is the use of :: operator in Kotlin?

2019-09-22 13:01发布

问题:

Please give me examples and usages of :: operator in Kotlin

回答1:

One example: It's for function references, that can be used alternatively to lambdas in many places:

 //Function expecting a lambda to be passed
fun <T> applyToList(list: List<T>, func: (T) -> Boolean) = list.filter { it -> func(it) }

fun foo(i: Int): Boolean = i > 3
//call applyToList with reference to foo()
applyToList(list, ::foo)

Or the same with lambda:

 applyToList(sub) { it > 3 }


回答2:

I found this one used while using intent

 val intent = Intent(this,MainActivity::class.java)
 startActivity(intent)


标签: kotlin