【问题标题】:Kotlin's reduce() function with different typesKotlin 不同类型的 reduce() 函数
【发布时间】:2018-06-16 10:56:54
【问题描述】:

我正在查看数组扩展函数,发现reduce()一个

inline fun <S, T: S> Array<out T>.reduce(operation: (acc: S, T) -> S): S {
    if (isEmpty())
        throw UnsupportedOperationException("Empty array can't be reduced.")
    var accumulator: S = this[0]
    for (index in 1..lastIndex) {
        accumulator = operation(accumulator, this[index])
    }
    return accumulator
}

在这里,S 类型的 accumulator 变量分配有数组中的第一个元素,类型为 T

无法理解具有两种数据类型的 reduce() 函数的真实用例。这里合成的例子实际上没有任何意义。

open class A(var width: Int = 0)
class B(width: Int) : A(width)

val array = arrayOf(A(7), A(4), A(1), A(4), A(3))
val res = array.reduce { acc, s -> B(acc.width + s.width) }

似乎大多数具有此功能的现实生活用例都使用此签名:

inline fun <T> Array<out T>.reduce(operation: (acc: T, T) -> T): T

您能否提供一些示例,其中reduce() 函数可用于不同类型。

【问题讨论】:

    标签: functional-programming kotlin


    【解决方案1】:

    这是一个例子:

    interface Expr {
        val value: Int
    }
    
    class Single(override val value: Int): Expr
    
    class Sum(val a: Expr, val b: Expr): Expr {
        override val value: Int
            get() = a.value + b.value
    }
    
    fun main(args: Array<String>) {
        val arr = arrayOf(Single(1), Single(2), Single(3));
        val result = arr.reduce<Expr, Single> { a, b -> Sum(a, b) }
        println(result.value)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2018-01-17
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      • 2018-10-03
      相关资源
      最近更新 更多