问题
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!
回答1:
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.
来源:https://stackoverflow.com/questions/7122558/scala-type-mismatch-problem-expected-map-found-scala-collection-mutable-hashma