https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

Son

10/19/2020, 4:29 PM
https://pl.kotl.in/Fa9favTpr I was getting this error and as a newbie I had a hard time determining why I could not do this (i.e. treating lambda as a function reference). Should the compiler error be more helpful?
Copy code
fun fn1(x: Int): Boolean = x % 2 == 0
fun fn2(x: Int): Boolean { return x % 2 == 0 }

fun main () {
    val listNum = listOf(1, 2, 3, 4, 5, 6)
    val fn3: (Int) -> Boolean = { it % 2 == 0 }

    println(listNum.filter(::fn1)) // compiles and outputs [2, 4, 6]
    println(listNum.filter(::fn2)) // compiles and outputs [2, 4, 6]
    println(listNum.filter(fn3)) // compiles and outputs [2, 4, 6]

    // e: org.jetbrains.kotlin.util.KotlinFrontEndException: Exception while analyzing expression at (17,13)
    println(listNum.filter(::fn3)) // Error
}
r

Razvan

10/19/2020, 4:34 PM
::
references a function
val fn3
declares a variable not a function so you can't use ::
s

Son

10/19/2020, 4:37 PM
Thanks. I read that after I was experimenting. My question is of the error message from the compiler isn’t helpful
IntelliJ
r

Razvan

10/19/2020, 4:43 PM
Yep looks like a bug 🙂
v

Vampire

10/19/2020, 4:47 PM
Well, that's obvious, isn't it? The message even tells you to report this as bug. 😄
s

Son

10/19/2020, 4:48 PM
Except there is not icon on the bottom right and the image link is broken 😆
v

Vampire

10/19/2020, 4:49 PM
And regarding
why I could not do this (i.e. treating lambda as a function reference).
Of course you can do this, or your second line would not work. Your problem is, that you already have the function reference in the variable fn3 and with
::fn3
you make a reference to the function reference, namely a reference to the variable
fn3
.
Except there is not icon on the bottom right and the image link is broken
Well, that's probably a second error you should report. 🙂
s

Son

10/19/2020, 4:49 PM
That was my mistake. Still learning the language
v

Vampire

10/19/2020, 4:49 PM
project KT, this error is most likely coming from the Kotlin plugin, not from IntelliJ itself
r

Razvan

10/19/2020, 4:58 PM
The error is more usefull if you use
::fun3.get()
Unsupported [References to variables aren't supported yet]
that's the way you should reference properties, but as this is a var is unsupported .. yet.
s

Son

10/19/2020, 5:46 PM
If you are still following along, I’ve opened two issues: https://youtrack.jetbrains.com/issue/KT-42795 https://youtrack.jetbrains.com/issue/KTIJ-257
3 Views