Scala:从一种类型的集合到另一种类型的收益
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6800520/
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
Scala: Yielding from one type of collection to another
提问by Zecrates
Concerning the yieldcommand in Scala and the following example:
关于Scala 中的yield命令和以下示例:
val values = Set(1, 2, 3)
val results = for {v <- values} yield (v * 2)
Ps. I know the example does not following the recommended functional way (which would be to use map), but it is just an example.
附言。我知道该示例没有遵循推荐的功能方式(即使用map),但这只是一个示例。
回答by missingfaktor
The forcomprehensions are translated by compiler to map/flatMap/filtercalls using thisscheme.
的for内涵是由编译器来编译map/ flatMap/filter使用调用这个方案。
This excellent answer by Danielanswers your first question.
Daniel 的这个出色回答回答了您的第一个问题。
To change the type of result collection, you can use collection.breakout(also explained in the post I linked above.)
要更改结果集合的类型,您可以使用collection.breakout(也在我上面链接的帖子中进行了解释。)
scala> val xs = Set(1, 2, 3)
xs: scala.collection.immutable.Set[Int] = Set(1, 2, 3)
scala> val ys: List[Int] = (for(x <- xs) yield 2 * x)(collection.breakOut)
ys: List[Int] = List(2, 4, 6)
You can convert a Setto a Listusing one of following ways:
您可以使用以下方式之一将 a 转换Set为 a List:
scala> List.empty[Int] ++ xs
res0: List[Int] = List(1, 2, 3)
scala> xs.toList
res1: List[Int] = List(1, 2, 3)
Recommended read:The Architecture of Scala Collections
推荐阅读:Scala 集合的架构
回答by Kim Stebel
If you use map/flatmap/filterinstead of for comprehensions, you can use scala.collection.breakOutto create a different type of collection:
如果使用map/ flatmap/filter而不是为解析,你可以使用scala.collection.breakOut来创建不同类型的集合:
scala> val result:List[Int] = values.map(2*)(scala.collection.breakOut)
result: List[Int] = List(2, 4, 6)
If you wanted to build your own collection classes (which is the closest thing to "replicating yield" that makes any sense to me), you should have a look at this tutorial.
如果你想构建你自己的集合类(这是最接近“复制产量”的东西,对我来说很有意义),你应该看看这个教程。
回答by user3613516
Try this:
试试这个:
val values = Set(1, 2, 3)
val results = for {v <- values} yield (v * 2).toList

