好的,我知道最好不要使用空值作为设计选择,但在这种情况下我必须这样做。为什么以下不能编译?
def test[T<:AnyRef](o :Option[T]) :T = o getOrElse null
Error:(19, 53) type mismatch;
found : Null(null)
required: T
Note: implicit method foreignKeyType is not applicable here because it comes after the application point and it lacks an explicit result type
def test[T<:AnyRef](o :Option[T]) :T = o getOrElse null
^
最佳答案
Null 是所有引用类型的子类型,但 T 是 AnyRef 的子类型这一事实并不能保证 T 是引用类型——特别是,Nothing 是不包含 null 的 AnyRef 的子类型。
如果添加下限,您的代码有效:
def test[T >:Null <:AnyRef](o :Option[T]) :T = o getOrElse null;
有用:
scala> def test[T >:Null <:AnyRef](o :Option[T]) :T = o getOrElse null;
test: [T >: Null <: AnyRef](o: Option[T])T
scala>
scala>
scala> test(None)
res0: Null = null
scala> test(Some(Some))
res1: Some.type = Some
关于scala - null 作为类型参数的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27399205/