【问题标题】:References to variables aren't supported yet in Kotlin higher order functionKotlin 高阶函数尚不支持对变量的引用
【发布时间】:2021-09-28 14:09:38
【问题描述】:

我了解在尝试实现以下代码时出现的错误。

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) 行。

提前致谢。

【问题讨论】:

  • val some = Something { some1.square(it) }?
  • 谢谢@Slaw。这就是我要找的。喜欢它。
  • 在我看来,avocato 的回答提供了一个更好的方法

标签: kotlin


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-07-23
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多