Scala/Java interop: class type not converted?

陌路散爱 提交于 2019-12-08 07:09:15

问题


The javafx api is defined like this:

void addListener(ChangeListener<? super java.lang.Boolean> listener)

The following code..

new TextArea().focusedProperty.addListener(new ChangeListener[Boolean]() {
  def changed(observable: ObservableValue[_ <: Boolean], oldValue: Boolean, newValue: Boolean) {
  }
})

..gives this error:

overloaded method value addListener with alternatives: (javafx.beans.value.ChangeListener[_ >: java.lang.Boolean])Unit (javafx.beans.InvalidationListener)Unit cannot be applied to (java.lang.Object with javafx.beans.value.ChangeListener[Boolean])

If I use java.lang.Boolean instead of Boolean, it works, but not with scala's Boolean. Why is that? Is it possible to use this api without having to type the fully qualified name?


回答1:


The problem is that in Scala, Boolean <: AnyVal <: Any, while java.lang.Boolean <: AnyRef <: Any. Since <? super java.lang.Boolean> means java.lang.Boolean or any superclass of it, you must fall into the AnyRef side of things. Unboxing is not enough; Boolean still places you on the AnyVal side of the type hierarchy even if you would box it into a java.lang.Boolean.



来源:https://stackoverflow.com/questions/11377350/scala-java-interop-class-type-not-converted

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