null 作为类型参数的实例

2024-01-05

好吧,我知道最好不要使用空值作为设计选择,但在这种情况下我必须这样做。为什么以下内容不能编译?

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

null 作为类型参数的实例 的相关文章

随机推荐