Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

References to variables aren't supported yet in Kotlin higher order function

Tags:

kotlin

I understand the error while I was trying to achieve the following code.

class Something(val foo: (x: Int) -> Int){
    fun xyz(a: Int){
        print("result: ${foo(a)}")
    }
}

fun main() {
    val some1 = Something1()
    val some = Something(::some1.square)
    val x = some.xyz(10)
}

class Something1{
    fun square(x: Int) = x*x    
}

I was just wondering if there is any workaround to achieve the line Something(::some1.square).

Thanks in advance.

like image 874
sadat Avatar asked Oct 18 '25 07:10

sadat


2 Answers

What you are trying to achieve is currently impossible in Kotlin. You can either try this val some = Something(some1::square) or @Slaw answer.

like image 183
avocato Avatar answered Oct 20 '25 07:10

avocato


Just for the reference if anybody lands here with the same question:

We can change fun to var, and use it as plain variable

class Something(val foo: (x: Int) -> Int){
    fun xyz(a: Int){
        print("result: ${foo(a)}")
    }
}

fun main() {
    val some1 = Something1()
    val some = Something(some1.square) // removed ::
    val x = some.xyz(10)
}

class Something1{
    //fun square(x: Int) = x*x  // changed to val
    val square =  { x: Int ->  x*x }
}
like image 37
HawajRambo Avatar answered Oct 20 '25 05:10

HawajRambo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!