我有一个Java界面,看起来大致是这样的:实现Scala的Java接口,使用泛型,并返回null
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.
有什么办法,使这项工作?
[尝试此处(HTTP://计算器。com/questions/10065962/how-to-a-function-in-scala) – BevynQ
@BevynQ:正如我在描述中写的,我尝试的第一件事是'T>:Null',但这会导致第二个错误。 –
我不知道scala,但它支持这种构造吗? 'barOpt。 orNull'? –
fge