Scala类型不匹配问题(预期是Map,发现是scala.collection.mutable.HashMap)
我仍然是一个新手 Scala 程序员,如果这个问题看起来很幼稚,我很抱歉,但我搜索了一段时间并没有找到解决方案。我正在使用 Scala 2.8,并且我有一个类 PXGivenZ 定义为:
class PXGivenZ (val x:Int, val z:Seq[Int], val values: Map[Seq[Int], Map[Int, Double]] ){...}
当我尝试将该类的一个元素实例化到另一个程序块中时,如下所示:
// 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)
我收到以下错误:
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)
^
显然有一些我不明白的内容: 如何Map[Seq[Int],Map[Int,Double]] 与 HashMap[Seq[Int], HashMap[Int,Double]] 不同吗?或者“可变”类出了什么问题?
预先感谢任何愿意帮助我的人!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
默认情况下,在 scala 文件中导入的
Map
是scala.collection.immutable.Map
而不是scala.collection.Map
。当然,就您而言,HashMap 是一个可变映射,而不是不可变映射。因此,如果您希望
Map
在文件中引用scala.collection.Map
,则必须显式导入它:这种选择的原因是您不会操作不可变结构和可变结构以同样的方式。因此,scala 默认情况下推断您将使用“最安全”的不可变结构。如果您不想这样做,则必须明确更改它。
By default, the
Map
that is imported in a scala file isscala.collection.immutable.Map
and notscala.collection.Map
. And of course, in your case, HashMap is a mutable map, not an immutable one.Thus if you want that
Map
refers toscala.collection.Map
in your file, you have to import it explicitely: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.