我有一个大致如下所示的 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
这是有道理的, typeT是不受限制的,它可能是 anInt或其他一些不能是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.
有什么办法可以使这项工作?