简体   繁体   中英

Using Scala extension of immutable class in Java

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM