Scala for understanding returning an ordered map

How can I use for an understanding that returns something that I can assign to an ordered map? This is a simplification of the code that I have:

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)

I need to make sure that my result is an ordered Map, in the root layout order due to understanding.

With the above, I get an error:

error: type mismatch;
found   : scala.collection.mutable.Buffer[(String,Bar)]
required: scala.collection.immutable.ListMap[String,Bar]
foo <- myList

This compiles:

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

but then I assume that the map will not be ordered, and I need an explicit call toMap.

How can i achieve this?

+3
source share
2 answers

You can achieve this using the companion object of the ListMap class, as shown below:

class Bar
class Foo(val name: String, val bar: Bar)
val myList: java.util.List[Foo] = ...
val result = ListMap((for(foo <- myList) yield (foo.name, foo.bar)):_*)
+4
source

collection.breakOut - ,

val result: collection.immutable.ListMap[String, Bar] = 
  myList.map{ foo => (foo.name, foo.bar) }(collection.breakOut)

for-comprehension, :

val result: collection.immutable.ListMap[String, Bar] = {
  for { foo <- myList } yield (foo.name, foo.bar)
}.map(identity)(collection.breakOut)

Scala 2.8 breakOut collection.breakOut.

+7

Source: https://habr.com/ru/post/1767302/


All Articles