Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin reduce operator seems to not work

Tags:

kotlin

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.

like image 215
Cata D Avatar asked Dec 11 '22 14:12

Cata D


2 Answers

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 -> "" }
like image 161
mfulton26 Avatar answered May 23 '23 15:05

mfulton26


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.

like image 20
Cristian Avatar answered May 23 '23 15:05

Cristian