[英]Using Scala extension of immutable class in Java
I have a Scala class EMCC
which extends TreeMap[Long,HashSet[DSFrame]]
我有一个扩展TreeMap[Long,HashSet[DSFrame]]
的Scala类EMCC
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. 我有一个Java类,我试图创建一个EMCC
并为其添加一个新的键值对。 I can create a new EMCC instance fine, but since TreeMap is immutable, I cannot simply call 我可以很好地创建一个新的EMCC实例,但由于TreeMap是不可变的,我不能简单地调用
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. 尝试将插入结果转换为EMCC仅产生相同的错误。
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. 我注意到的一件事是它报告结果的键是对象,这是奇怪的,因为在这种情况下key
很长,但我不确定这是否相关。
If you want to extend your TreeMap with domain-specific methods I see two possible solutions. 如果您想使用特定于域的方法扩展TreeMap,我会看到两种可能的解决方案。
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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.