Search code examples
lambdakotlinfunctional-programmingjvm

Kotlin: why a function can't be stored in a variable?


Why do i have to use function reference to store a function into a variable:

fun someFunction(i: Int): Unit = println(i)
val funVal = someFunction  // Compile error!
val funVal2 = ::someFunction // Function reference works fine

But I can store lambda in a variable directly:

val someLambda: (Int) -> Unit = { i: Int -> println(i) }

Solution

  • It is about correct syntax. Or more precisely, about the ability of the compiler to understand what you are trying to tell it!

    When you look at your different examples, you can find that the accepted cases use specific chars, like the colon for example. That makes it simply easier to deduct what the code is meant to say.

    So, one possible reason could be a trade off. Sure, when you have

    val a = b
    

    you could allow b to be a method reference. But what if you wanted to call b() instead?! The "lexicographic" distance between b and b() is pretty small!

    So to not allow for that syntax makes it a) easier to parse code, and b) harder for you to have small typos change the meaning of your code!