scala Scala类型不匹配问题(预期Map,发现scala.collection.mutable.HashMap)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7122558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala type mismatch problem (expected Map, found scala.collection.mutable.HashMap)
提问by Alberto
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:
我仍然是 Scala 程序员的新手,很抱歉,如果这个问题看起来很幼稚,但我搜索了一段时间并没有找到解决方案。我正在使用 Scala 2.8,并且我有一个类 PXGivenZ 定义为:
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?
显然我没有得到一些东西:Map[Seq[Int],Map[Int,Double]] 与 HashMap[Seq[Int], HashMap[Int,Double]] 有何不同?还是“可变”类有问题?
Thanks in advance to anyone who will help me!
在此先感谢任何愿意帮助我的人!
回答by Nicolas
By default, the Mapthat is imported in a scala file is scala.collection.immutable.Mapand not scala.collection.Map. And of course, in your case, HashMap is a mutable map, not an immutable one.
默认情况下,Map在 Scala 文件中导入的 是scala.collection.immutable.Map而不是scala.collection.Map。当然,就您而言, HashMap 是可变映射,而不是不可变映射。
Thus if you want that Maprefers to scala.collection.Mapin your file, you have to import it explicitely:
因此,如果你想在你的文件中Map引用scala.collection.Map它,你必须明确地导入它:
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.
这种选择的原因是您不会以相同的方式操作不可变和可变结构。因此,scala 默认推断您将使用“最安全”的不可变结构。如果您不想这样做,则必须明确更改它。

