1

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?

k314159
  • 5,051
  • 10
  • 32

1 Answers1

2

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
gpunto
  • 2,573
  • 1
  • 14
  • 17
  • Doing so yields the following in my IntelliJ: `'matches1' is a member and an extension at the same time. References to such elements are not allowed`, see [this question](https://stackoverflow.com/questions/46562039/kotlin-member-and-extension-at-the-same-time) for more. – Endzeit Jun 12 '22 at 11:54
  • @Endzeit Did you put `matches1` and `matches2` in a class? I do not get the error if I put them at top level. – Sweeper Jun 12 '22 at 11:59
  • @Sweeper: or in a scratch file, where the top level only seems to be top level. – lukas.j Jun 12 '22 at 12:02
  • @Sweeper Huh, that's interesting. I indeed used a scratch file. – Endzeit Jun 12 '22 at 12:39
  • @lukas.j Thanks for pointing that out. – Endzeit Jun 12 '22 at 12:40