Why does Scala complain about illegal inheritance when there are raw types in the class hierarchy?

我们两清 提交于 2019-12-04 03:54:35

问题


I'm writing a wrapper that takes a Scala ObservableBuffer and fires events compatible with the Eclipse/JFace Databinding framework.

In the Databinding framework, there is an abstract ObservableList that decorates a normal Java list. I wanted to reuse this base class, but even this simple code fails:

val list = new java.util.ArrayList[Int]
val obsList = new ObservableList(list, null) {}

with errors:

illegal inheritance; anonymous class $anon inherits different type instances of trait Collection: java.util.Collection[E] and java.util.Collection[E]
illegal inheritance; anonymous class $anon inherits different type instances of trait Iterable: java.lang.Iterable[E] and java.lang.Iterable[E]

Why? Does it have to do with raw types? ObservableList implements IObservableList, which extends the raw type java.util.List. Is this expected behavior, and how can I work around it?


回答1:


Having a Java raw type in the inheritance hierarchy causes this kind of problem. One solution is to write a tiny bit of Java to fix up the raw type as in the answer for Scala class cant override compare method from Java Interface which extends java.util.comparator

For more about why raw types are problematic for scala see this bug http://lampsvn.epfl.ch/trac/scala/ticket/1737 . That bug has a workaround using existential types that probably won't work for this particular case, at least not without a lot of casting, because the java.util.List type parameter is in both co and contra variant positions.




回答2:


From looking at the javadoc the argument of the constructor isn't parameterized.

I'd try this:

val list = new java.util.ArrayList[_]
val obsList = new ObservableList(list, null) {}


来源:https://stackoverflow.com/questions/4991671/why-does-scala-complain-about-illegal-inheritance-when-there-are-raw-types-in-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!