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

Cat*_*a D 4 kotlin

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

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

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

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

有人见过这个吗?...不确定这是否是在线工具的错误,或者它确实是错误的.

mfu*_*n26 8

科特林标准库有两种不同类型的蓄电池的:foldreduce.它看起来像你想要的fold:

collection.fold(initial = "") { accumulator: String, element: Int -> "" }
Run Code Online (Sandbox Code Playgroud)


Cri*_*ian 5

您不能reduce收集字符串集合的整数.这些编译:

// reduce to int
collection.reduce { x:Int, y:Int -> 0 }

// map to string first, then reduce
collection.map { "" }.reduce { x:String, y:String -> "" }
Run Code Online (Sandbox Code Playgroud)

如果您查看reduce签名,这一点会更清楚:

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

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