开发者

Yield String from List[Char]

I have a l: List[Char] of characters which I want开发者_如何学Go 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!


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.


You can use the following:

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

See this question for more information about breakOut.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜