【发布时间】:2013-06-23 01:41:40
【问题描述】:
我有一个大致如下所示的 Java 接口:
public interface Foo {
public <T> T bar();
}
我想在 Scala 中实现这个接口,我的所有代码都使用Option。但是,由于该接口将由 Java 用户使用,因此我想返回 null 而不是 None。我尝试了以下方法:
class FooImpl extends Foo {
def bar[T](): T = {
val barOpt: Option[T] = getBar()
barOpt.orNull
}
}
这会导致以下编译错误:
Expression of type Null does not conform to expected type T
这是有道理的,类型T 是不受限制的,它可以是Int 或其他不能是null 的类型。没问题,添加T >: Null就完成了,对吧?
class FooImpl extends Foo {
def bar[T >: Null](): T = {
val barOpt: Option[T] = getBar()
barOpt.orNull
}
}
不,仍然没有骰子。现在你得到一个新的编译错误:
[error] method bar has incompatible type
您似乎无法对T 应用任何限制并仍然实现该接口。
接下来,我尝试使用asInstanceOf:
class FooImpl extends Foo {
def bar[](): T = {
val barOpt: Option[T] = getBar()
barOpt.orNull.asInstanceOf[T]
}
}
但这只会带来另一个错误:
Cannot prove that Null <:< T.
有什么办法可以做到这一点吗?
【问题讨论】:
-
@BevynQ:正如我在描述中所写,我尝试的第一件事是
T >: Null,但这导致了第二个错误。 -
我不知道scala,但它支持这种构造吗?
barOpt.<T>orNull?