Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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])]
like image 768
bauhaus9 Avatar asked Oct 31 '25 08:10

bauhaus9


1 Answers

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")
  )
}
like image 64
Daryl Odnert Avatar answered Nov 02 '25 23:11

Daryl Odnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!