加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – null作为类型参数的实例

发布时间:2020-12-16 10:06:37 所属栏目:安全 来源:网络整理
导读:好吧,我知道比使用null作为设计选择更好,但在这种情况下我必须这样做.为什么以下不编译? def test[T:AnyRef](o :Option[T]) :T = o getOrElse nullError:(19,53) type mismatch; found : Null(null) required: T Note: implicit method foreignKeyType is n
好吧,我知道比使用null作为设计选择更好,但在这种情况下我必须这样做.为什么以下不编译?

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是AnyRef的子类型,它不包含null.

如果添加下限,则代码有效:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读