试图在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
有人看过这个吗?...不确定这是否是在线工具的错误,或者它是否真的出错了。
答案 0 :(得分:7)
Kotlin Standard Library有两种不同类型的累加器:fold
和reduce
。看起来你想要fold
:
collection.fold(initial = "") { accumulator: String, element: Int -> "" }
答案 1 :(得分:6)
你不能using (var file = File.Exists(path) ? File.Open(path, FileMode.Append) : File.Open(path, FileMode.CreateNew))
using (var stream = new StreamWriter(file))
stream.WriteLine(_message);
一组字符串的整数集合。这些编译:
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
,S
或超T
。