Yield String from List[Char]

xyz picture xyz · May 28, 2011 · Viewed 30k times · Source

I have a l: List[Char] of characters which I want to concat and return as a String in one for loop.

I tried this

val x: String = for(i <- list) yield(i)

leading to

 error: type mismatch;  
 found   : List[Char]  
 required: String

So how can I change the result type of yield?

Thanks!

Answer

Jean-Philippe Pellet picture Jean-Philippe Pellet · May 28, 2011

Try this:

val x: String = list.mkString

This syntax:

for (i <- list) yield i

is syntactic sugar for:

list.map(i => i)

and will thus return an unchanged copy of your original list.