我查看了数组扩展函数,发现
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
}
这里是
accumulator
类型的变量
S
使用类型为的数组中的第一个元素分配
T
.
无法将我的头环绕在
减少()
具有两种数据类型的函数。这里的合成例子实际上没有任何意义。
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
你能提供一些例子吗?
减少()
函数可以用于不同的类型。