scala 从列表中产生字符串[Char]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6162524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Yield String from List[Char]
提问by xyz
I have a l: List[Char] of characters which I want to concat and return as a String in one for loop.
我有 al: List[Char] 我想在一个 for 循环中连接并作为字符串返回的字符。
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?
那么我怎样才能改变yield的结果类型呢?
Thanks!
谢谢!
回答by Jean-Philippe Pellet
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.
因此将返回原始list.
回答by Daniel C. Sobral
You can use the following:
您可以使用以下内容:
val x: String = (for(i <- list) yield(i))(collection.breakOut)
See this questionfor more information about breakOut.
有关 breakOut 的更多信息,请参阅此问题。
回答by jfuentes
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.
您可以使用三个 mkString 重载中的任何一个。基本上它通过每个元素的 toString 方法将集合转换为平面字符串。重载在每个元素之间添加自定义分隔符。
It is a Iterable's method, so you can also use it in Map or Set.
它是一个 Iterable 的方法,所以你也可以在 Map 或 Set 中使用它。
See http://www.scala-lang.org/api/2.7.2/scala/Iterable.htmlfor more details.
有关更多详细信息,请参阅http://www.scala-lang.org/api/2.7.2/scala/Iterable.html。

