我对使用 Scala 编程完全陌生,但遇到以下问题:
我需要一个可以包含许多数据类型(Int、String 等)的 HashMap。在 C++ 中,我会使用 BOOST 的 MultiMap。我听说在 Scala 中有一个 MultiMap trait 可用。基本上我想要的是以下内容:
val map = HashMap[String, ListBuffer[_]]
ListBuffer 元素的具体数据类型将在运行时确定。当我在控制台中测试此实现时,以下工作:
scala> val a = new HashMap[String, ListBuffer[_]]()
a: scala.collection.mutable.HashMap[String,scala.collection.mutable.ListBuffer[_]] = Map()
scala> val b = new ListBuffer[String]()
b: scala.collection.mutable.ListBuffer[String] = ListBuffer()
scala> val c = new ListBuffer[Int]()
c: scala.collection.mutable.ListBuffer[Int] = ListBuffer()
scala> b += "String"
res0: b.type = ListBuffer(String)
scala> c += 1
res1: c.type = ListBuffer(1)
scala> a += "String Buffer" -> b
res2: a.type = Map((String Buffer,ListBuffer(String)))
scala> a += "This is an Int Buffer" -> c
res3: a.type = Map((String Buffer,ListBuffer(String)), (This is an Int Buffer,ListBuffer(1)))
所以基本上它可以工作。我的第一个问题是,是否有可能在不使用 ListBuffer 作为间接层的情况下在 Scala 中实现相同的行为。
例如,获取具有以下内容的 Map: Map((String, 1),(String, "String value"), ...)
当我现在尝试使用上面的 ListBuffer-Implementation 时,我收到以下类型不匹配错误:
found : _$1 where type _$1
required: _$3 where type _$3
我基本上是在尝试执行以下操作:
我使用迭代器来迭代地图的键:
var valueIds = new ListBuffer[Int]()
val iterator = map.keys
iterator.foreach(key => { valueIds += setValue((map.apply(key)).last) }
setValue 返回 Int 并且是一个必须对 ListBuffers 最后一个元素做某事的方法。
有谁知道如何解决上述类型不匹配?
谢谢你的帮助!
问候