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.
What you are trying to achieve is currently impossible in Kotlin. You can either try this val some = Something(some1::square)
or @Slaw answer.
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 }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With