Kotlin减少运营商似乎不工作

试图在Kotlin的在线学习工具上运行这个例子:

fun toJSON(collection: Collection<Int>): String { val str = collection.reduce{ a:String, b:Int -> ""} return str.toString() } 

但是,它似乎并没有编译,吐出这个错误:

Error:(2, 25) Type parameter bound for T in inline fun <S, T : S> Iterable<T>.reduce(operation: (S, T) -> S): S is not satisfied: inferred type Int is not a subtype of String

任何人看到这个?…不知道是否是在线工具的错误,或者如果它实际上是错误的。

您不能reduce整数的集合reduce到一个字符串集合。 这些编译:

 // reduce to int collection.reduce { x:Int, y:Int -> 0 } // map to string first, then reduce collection.map { "" }.reduce { x:String, y:String -> "" } 

如果您看一下reduce签名,这是更清楚的:

fun <S, T: S> Iterable<T>.reduce(operation: (S, T) -> S): S

它基本上运行在T类型的集合上,产生一个TT的超类型S

Kotlin标准库有两种不同类型的累加器: foldreduce 。 看起来你想要fold

 collection.fold(initial = "") { accumulator: String, element: Int -> "" }