Scala/Java互操作:类类型未转换? [英] Scala/Java interop: class type not converted?

查看:76
本文介绍了Scala/Java互操作:类类型未转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

javafx api的定义如下:

The javafx api is defined like this:

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

以下代码..

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

..给出此错误:

使用替代方法重载了方法值addListener: (javafx.beans.value.ChangeListener [_>:java.lang.Boolean])单位 (javafx.beans.InvalidationListener)单元不能应用于 (带有javafx.beans.value.ChangeListener [Boolean]的java.lang.Object)

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])

如果我使用java.lang.Boolean而不是Boolean,它可以工作,但不适用于scala的布尔值.这是为什么?是否可以使用此api而不必键入完全限定的名称?

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?

推荐答案

问题是在Scala中,Boolean <: AnyVal <: Any,而在java.lang.Boolean <: AnyRef <: Any中.由于<? super java.lang.Boolean>表示它的java.lang.Boolean any 超类,因此您必须属于事物的AnyRef侧.开箱是不够的; Boolean仍将您置于类型层次结构的AnyVal侧,即使您将其装在java.lang.Boolean中也是如此.

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.

这篇关于Scala/Java互操作:类类型未转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆