Kotlin的reduce()函数具有不同的类型 [英] Kotlin's reduce() function with different types
本文介绍了Kotlin的reduce()函数具有不同的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在浏览数组扩展功能,发现reduce()
一个
I was looking through array extension functions and found reduce()
one
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
的数组中的第一个元素.
here the accumulator
variable of type S
assigned with first element from the array with type T
.
不能用两种数据类型来解决reduce()
函数的实际用例.这里的综合示例实际上没有任何意义.
Can't wrap my head around the real use case of reduce()
function with two data types. Here synthetic example which actually doesn't make any sense.
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) }
似乎大多数具有此功能的现实生活用例都使用以下签名:
Seems most real life use cases with this function use this signature:
inline fun <T> Array<out T>.reduce(operation: (acc: T, T) -> T): T
您能否提供一些示例,其中reduce()
函数在不同类型上可能有用.
Can you help with providing some examples, where reduce()
function can be useful with different types.
推荐答案
以下是示例:
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)
}
这篇关于Kotlin的reduce()函数具有不同的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文