Kotlin减少操作员似乎不起作用

时间:2016-11-09 18:10:51

标签: 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

有人看过这个吗?...不确定这是否是在线工具的错误,或者它是否真的出错了。

2 个答案:

答案 0 :(得分:7)

Kotlin Standard Library有两种不同类型的累加器:foldreduce。看起来你想要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类型的集合进行操作,并生成TS或超T

相关问题