Why does Kotlin need function reference syntax?

Because Java (and, therefore, Kotlin) uses separate namespaces for fields and methods, you need :: to avoid ambiguities. Example:

val isOdd : (Int) -> Boolean = { x -> x % 2 != 0 }
fun isOdd(x: Int): Boolean {
    return x % 2 != 0
}

val odds = listOf(1,2,3).filter(isOdd) // uses the val version
val otherOdds = listOf(1,2,3).filter(::isOdd) // uses the fun version

Kotlin language design tries to avoid ambiguous situations where some absence of something could be both correct and incorrect syntax at the same time. For example if you allowed the proposed syntax:

isOdd     // error, function invocation expected isOdd(...)
isOdd     // not error, you have a function reference

The :: is a clear signal as to the intent. Because of this, you get only an error in the isOdd case because you now have possibilities that do not overlap:

isOdd      // error, function invocation expected isOdd(...)
::isOdd    // function reference
isOdd()    // error, missing parameter x
isOdd(x)   // function call

This is why Kotlin avoids things that lead to ambiguous states. Your eyes can also quickly pick up the problem, just as the IDE and static analysis can, just as the compiler does. If you start allowing this looser syntax you will start running into compounded ambiguities such as when using as infix functions and so on. Language design is more complicated than "oh, let's make them type less characters" because the complexity matrix is much larger than you imagine if you only look at one use case ignoring all the others.

Tags:

Kotlin