Cata D
Cata D

Reputation: 135

Kotlin reduce operator seems to not work

Tried to run this example on Kotlin's online learning tool:

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

However, it doesn't seem to compile, spitting this error:

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

Anyone seen this?...not sure if it's an error with the online tool or if it's actually something wrong.

Upvotes: 4

Views: 1854

Answers (2)

mfulton26
mfulton26

Reputation: 31224

The Kotlin Standard Library has two different types of accumulators: fold and reduce. It looks like you want fold:

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

Upvotes: 8

Cristian
Cristian

Reputation: 200080

You can't reduce a collection of ints to a collection of strings. These compile:

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

// map to string first, then reduce
collection.map { "" }.reduce { x:String, y:String -> "" }

This is clearer if you take a look at the reduce signature:

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

It basically operates on a collection of type T, and produces an S which is a T or a supertype of T.

Upvotes: 5

Related Questions