For a list of string, I do this:
val l = List("a", "r", "e")
l.reduceLeft((x, z) => x + z)
I don't know how to do it for a list of Chars. The following is a compile error:
val chs = List('a', 'r', 'e')
chs.reduceLeft[String]( (x,y) => String.valueOf(x) + String.valueOf(y))
Here's the type signature for reduceLeft:
def reduceLeft[B >: A](f: (B, A) => B): B
It requires that what you're reducing to be a subtype of the type that you're reducing from so in you're case Char is A and String is B which is not a subtype of Char.
You can do a foldLeft which will reduce your list and doesn't require the output to be a subtype of the input:
chs.foldLeft("")((x,y) => x + String.valueOf(y))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With