34

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!

soc
  • 27,983
  • 20
  • 111
  • 215
xyz
  • 341
  • 1
  • 3
  • 3

3 Answers3

78

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.

Jean-Philippe Pellet
  • 59,296
  • 21
  • 173
  • 234
4

You can use the following:

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

See this question for more information about breakOut.

Community
  • 1
  • 1
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
2

You can use any of the three mkString overloads. Basically it converts a collection into a flat String by each element's toString method. Overloads add custom separators between each element.

It is a Iterable's method, so you can also use it in Map or Set.

See http://www.scala-lang.org/api/2.7.2/scala/Iterable.html for more details.

jfuentes
  • 477
  • 5
  • 8