我有一個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