2016-11-09 35 views
3

想跑上科特林的在線學習工具,這個例子:科特林降低運營商似乎不起作用

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

任何人都看到了這個?...不知道它是否是在線工具的錯誤,或者如果它實際上是錯誤的。

回答

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 -> "" } 

這是清晰的,如果你看看在reduce簽名:

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

它基本上運行在T類型的集合,併產生S這是一個T或超類型T

5

Kotlin Standard Library有兩種不同類型的累加器:foldreduce。它看起來像你想fold

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