简体   繁体   中英

What do I need to change to make Scala 2.13 MultiDict work as a drop-in replacement for 2.12's MultiMap?

For Scala code < 2.13, I am using a MultiMap as defined here MultiMap . Using the example code found there, I was hoping to update it by simply replacing the code:

val mm = new HashMap[Int, Set[String]] with MultiMap[Int, String]

with

val mm2 = new HashMap[Int, Set[String]] with MultiDict[Int, String]

But instead I get the following error:

illegal inheritance; 
<$anon: Int => scala.collection.mutable.Set[String] 
with scala.collection.MultiDict[Int,String]> inherits different type instances of trait Iterable:
Iterable[(Int, String)] and Iterable[(Int, scala.collection.mutable.Set[String])]

What you'll want to do is:

  1. Instantiate a mutable MultiDict[K, V] .
  2. Add and remove items from that collection as needed via the methods inherited from the Growable[(K, V)] and Shrinkable[(K, V)] traits.
  3. Use the sets method on the instance when you need to access the collection as a Map[K, Set[V]] .

In the following example, both md1 and md2 are mutable MultiDict[Int, String] objects that are equivalent at the end of the code block:

locally {
  import scala.collection.mutable

  val md1 = mutable.MultiDict.empty[Int, String]
  md1.addOne(1 -> "one")
  md1.addOne(1 -> "uno")
  md1.addOne(2 -> "two")
  md1.addOne(2 -> "dos")

  val md2 = mutable.MultiDict.from[Int, String](
    Seq(1 -> "one", 1 -> "uno", 2 -> "two", 2 -> "dos")
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM