Home > Software design >  References to variables aren't supported yet in Kotlin higher order function
References to variables aren't supported yet in Kotlin higher order function

Time:09-28

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.

CodePudding user response:

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

  • Related