Scala: reduceLeft with string
It cannot work that way with reduceLeft
. Informally, you can view it reduceLeft
as a special case foldLeft
where the accumulated value is of the same type as the elements of the collection. Since in your case the type of the element Int
, and the accumulated value String
, cannot be used reduceLeft
in the way you used foldLeft
.
However, in this particular case, you can simply convert all elements Int
to the String
front and then shrink:
scala> xs.map(_.toString) reduceLeft(_+_)
res5: String = 12345
Note that this will throw an exception if the list is empty. This is another difference from foldLeft
, which handles the empty case just fine (since it has an explicit seed). It's also less efficient because we are creating a whole new collection (of strings) to shrink in place. In general, foldLeft
there is a much better choice here.
source to share