In the following example (also on Kotlin Playground), IntelliJ offers to change the lambda (as in the commented-out first line of main
) to a method reference (as shown in the second line of main
).
fun Int.matches1(n: Int): Boolean = TODO()
fun Int.matches2(n: Int): Boolean = TODO()
fun main() {
// val matches: Int.(Int) -> Boolean = { n -> matches1(n) }
val matches: Int.(Int) -> Boolean = ::matches1
}
The line containing the lambda works fine. However, if I try to use the method reference, the Kotlin compiler rejects it with Unresolved reference: matches1
. Why?
CodePudding user response:
You need to specify the receiver type, since you're trying to reference an extension function. It's similar to when you want to reference a function that belongs to a class. So this works:
val matches: Int.(Int) -> Boolean = Int::matches1