Kotlin reduce运算符似乎不起作用
尝试在Kotlin的在线学习工具上运行此示例:Kotlin reduce运算符似乎不起作用,kotlin,Kotlin,尝试在Kotlin的在线学习工具上运行此示例: fun toJSON(collection: Collection<Int>): String { val str = collection.reduce{ a:String, b:Int -> ""} return str.toString() } fun-toJSON(collection:collection):字符串{ val str=collection.reduce{a:String,b:Int->“
fun toJSON(collection: Collection<Int>): String {
val str = collection.reduce{ a:String, b:Int -> ""}
return str.toString()
}
fun-toJSON(collection:collection):字符串{
val str=collection.reduce{a:String,b:Int->“”
return str.toString()
}
但是,它似乎没有编译,因此出现了以下错误:
错误:(2,25)内联fun Iterable.reduce(操作:(S,T)->S)中为T绑定的类型参数
不满足:推断类型Int不是字符串的子类型
有人看到了吗?…不确定这是联机工具的错误还是实际出了什么问题。您不能
将整数集合减少为字符串集合。这些文件包括:
// reduce to int
collection.reduce { x:Int, y:Int -> 0 }
// map to string first, then reduce
collection.map { "" }.reduce { x:String, y:String -> "" }
如果您查看reduce
签名,这一点会更清楚:
funiterable.reduce(操作:(S,T)->S):S
它基本上在类型T
的集合上运行,并生成一个S
,它是T
或T
的超类型。它有两种不同类型的累加器:折叠
和减少
。看起来您想要:
collection.fold(initial = "") { accumulator: String, element: Int -> "" }