Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala type mismatch problem (expected Map, found scala.collection.mutable.HashMap)

I am still a newbie Scala programmer, so sorry if this question may look naive, but I searched for a while and found no solutions. I am using Scala 2.8, and I have a class PXGivenZ defined as:

class PXGivenZ (val x:Int, val z:Seq[Int], val values: Map[Seq[Int], Map[Int, Double]] ){...}

When I try to instantiate an element of that class into another block of program like this:

// x is an Int
// z is a LinkedList of Int
...
var zMap = new HashMap[Seq[Int], HashMap[Int, Double]]
...
val pxgivenz = new PXGivenZ(x, z, zMap)

I get the following error:

found   : scala.collection.mutable.HashMap[Seq[Int],scala.collection.mutable.HashMap[Int,Double]]
 required: Map[Seq[Int],Map[Int,Double]]
           val pxgivenz = new PXGivenZ(x, z, zMap) 
                                             ^

There is clearly something I don't get: how is a Map[Seq[Int],Map[Int,Double]] different from a HashMap[Seq[Int], HashMap[Int,Double]]? Or is something wrong with the "mutable" classes?

Thanks in advance to anyone who will help me!

like image 433
Alberto Avatar asked Aug 19 '11 13:08

Alberto


1 Answers

By default, the Map that is imported in a scala file is scala.collection.immutable.Map and not scala.collection.Map. And of course, in your case, HashMap is a mutable map, not an immutable one.

Thus if you want that Map refers to scala.collection.Map in your file, you have to import it explicitely:

import scala.collection.Map

The reason of this choice is that you will not manipulate an immutable and a mutable structure in the same way. Thus, scala infers by default that you will use immutable structure which are "most secure". If you don't want to do so, you must change it explicitly.

like image 61
Nicolas Avatar answered Sep 28 '22 08:09

Nicolas