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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- docker storage driver
- WebService(4):CXF Spring开发WebService,基于SOAP和RE
- yum [Errno 256] No more mirrors to try 解决方法
- 玩! 2 scala:在控制器代码中向表单添加错误
- 调用webservice总结
- 斯卡拉 – 为什么未来有副作用?
- Bootstrap之表格checkbox复选框全选
- angularjs – Angular JS无法在页面/路由更改上呈现社交媒体
- angular – 错误:找不到加载’ProfileDetailsComponent’的
- angularjs – 如何从$stateChangeStart访问UI-Router根状态