Scala类型不匹配问题(预期的Map,找到scala.collection.mutable.HashMap) [英] Scala type mismatch problem (expected Map, found scala.collection.mutable.HashMap)

查看:655
本文介绍了Scala类型不匹配问题(预期的Map,找到scala.collection.mutable.HashMap)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然是Scala的新手程序员,所以很抱歉,如果这个问题看起来很幼稚,但是我搜索了一段时间却没有找到解决方案.我正在使用Scala 2.8,并且将类PXGivenZ定义为:

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)

我收到以下错误:

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]]有何不同?还是可变"类出了问题?

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!

推荐答案

默认情况下,在scala文件中导入的Mapscala.collection.immutable.Map而不是scala.collection.Map.当然,就您而言,HashMap是可变的地图,而不是不可变的地图.

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.

因此,如果希望Map引用文件中的scala.collection.Map,则必须显式导入它:

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

import scala.collection.Map

之所以选择它,是因为您将不会以相同的方式操作不可变和可变的结构.因此,默认情况下,scala推断您将使用最安全"的不可变结构.如果您不想这样做,则必须显式更改它.

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类型不匹配问题(预期的Map,找到scala.collection.mutable.HashMap)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆