【问题标题】:Replace lamda in an extension function在扩展函数中替换 lamda
【发布时间】:2018-12-20 14:52:02
【问题描述】:

这是一个扩展函数:

fun <T, R> Collection<T>.fold(initial: R,  combine: (acc: R, nextElement: T) -> R): R {
    var accumulator: R = initial
    for (element: T in this) {
        accumulator = combine(accumulator, element)
    }
    return accumulator
}

是否可以用单独的函数替换作为函数的第二个参数。例如,看起来类似于这样的东西:

fun <T, R> Collection<T>.fold(initial: R, someFun)

fun someFun (acc: R, nextElement: T) -> R): R {
        var accumulator: R = initial
        for (element: T in this) {
            accumulator = combine(accumulator, element)
        }
        return accumulator
}

【问题讨论】:

    标签: kotlin kotlin-extension


    【解决方案1】:

    您可以使用两个冒号来传递对函数的引用:

    var collection = listOf<String>()
    collection.fold(3, ::someFun)
    
    fun <T, R> someFun(acc: R, nextElement: T): R {
        var accumulator: R = acc
        // ...
        return accumulator
    }
    

    【讨论】:

    • 你能告诉我如何使用我列出的代码来做到这一点,因为我似乎无法正确理解它。
    • 第一个代码块中的扩展函数确实可以编译。我直接从 Kotlin 文档中得到了这个。我想知道如何将您的解决方案用于该代码。
    【解决方案2】:

    我不确定您为什么需要以这种方式提取函数。有问题的所需代码无法编译并提出一个可行的替代方案,需要了解您的实际意图。

    例如,如果您不想在参数类型中拼写长函数签名,可能是因为您有很多此类函数采用该类型的函数参数并且您害怕在该签名中出错,您可以将功能类型声明提取到type alias

    typealias Combiner<R, T> = (acc: R, nextElement: T) -> R
    

    然后在函数声明中使用该类型别名:

    fun <T, R> Collection<T>.fold(initial: R, combine: Combiner<R, T>): R {
        var accumulator: R = initial
        for (element: T in this) {
            accumulator = combine(accumulator, element)
        }
        return accumulator
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多