ebr*_*hez 3 scala scala-2.8 scala-collections
如何使用for-comprehension返回可以分配给有序Map的内容?这是我所拥有的代码的简化:
class Bar
class Foo(val name: String, val bar: Bar)
val myList: java.util.List[Foo] = ...
val result: ListMap[String, Bar] =
for {
foo <- myList
} yield (foo.name, foo.bar)
Run Code Online (Sandbox Code Playgroud)
我需要确保我的结果是一个有序的Map,顺序是从for-comprehension返回的元组.
有了上述,我得到错误:
error: type mismatch;
found : scala.collection.mutable.Buffer[(String,Bar)]
required: scala.collection.immutable.ListMap[String,Bar]
foo <- myList
Run Code Online (Sandbox Code Playgroud)
这编译:
class Bar
class Foo(val name: String, val bar: Bar)
val myList: java.util.List[Foo] = ...
val result: Predef.Map[String, Bar] =
{
for {
foo <- myList
} yield (foo.name, foo.bar)
} toMap
Run Code Online (Sandbox Code Playgroud)
但后来我假设地图不会被排序,我需要一个明确的toMap调用.
我怎样才能做到这一点?
该collection.breakOut是在这样的情况下,你的好朋友,
val result: collection.immutable.ListMap[String, Bar] =
myList.map{ foo => (foo.name, foo.bar) }(collection.breakOut)
Run Code Online (Sandbox Code Playgroud)
如果使用for-comprehension表达很重要,它将按如下方式完成,
val result: collection.immutable.ListMap[String, Bar] = {
for { foo <- myList } yield (foo.name, foo.bar)
}.map(identity)(collection.breakOut)
Run Code Online (Sandbox Code Playgroud)
Scala 2.8 breakOut已经解释了collection.breakOut非常好.