質問

I have a Scala class EMCC which extends TreeMap[Long,HashSet[DSFrame]]

I have a Java class in which I am attempting to create an EMCC and add a new key-value pair to it. I can create a new EMCC instance fine, but since TreeMap is immutable, I cannot simply call

emcc.insert(key, value)

but must instead call

emcc = emcc.insert(key,value)

Attempting to compile this yields the following error:

error: incompatible types
[javac]             emcc = emcc.insert(key, value);
[javac]                               ^
[javac]   required: EMCC
[javac]   found:    TreeMap<Object,Set<DSFrame>>

Attempting to cast the insertion result to an EMCC only yields the same error.

How do I make these play well together?

One thing I notice is that it is reporting that the keys of the result are Objects, which is odd because in this situation key is a long, but I'm not sure if that's related.

役に立ちましたか?

解決

If you want to extend your TreeMap with domain-specific methods I see two possible solutions.

composition

class EMCC(private val map: TreeMap[Long, HashSet[DSFrame]] = TreeMap.empty[Long, HashSet[DSFrame]]) {
  def insert(key: Long, value: HashSet[DSFrame]) = new EMCC(map + (key -> value))
  def foo = map.size
}
var e = new EMCC
e = e.insert(23L, HashSet.empty[DSFrame])
println(e.foo)

or implicit classes

type EMCC = TreeMap[Long, HashSet[DSFrame]]
implicit class EmccExt(map: EMCC) {
  def foo = map.size
}
var e = new EMCC
e = e.insert(23L, HashSet.empty[DSFrame])
println(e.foo)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top