Kotlin 高阶函数中尚不支持对变量的引用



当我试图实现以下代码时,我理解了错误。

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    
}

我只是想知道是否有任何解决方法来实现Something(::some1.square)

提前感谢。

您想要实现的是目前在Kotlin中不可能实现的。你可以试试这个val some = Something(some1::square)或@沙拉的答案。

最新更新