我正在查看数组扩展函数,发现了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
}
这里将类型为T
的数组中的第一个元素赋值给类型为S
的accumulator
变量。
我无法理解使用两种数据类型的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()
函数的不同类型的示例吗?