null作为类型参数的实例

null作为类型参数的实例

本文介绍了null作为类型参数的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  def test [T  
错误:(19,53)类型不匹配;
找到:Null(null)
required:T
注意:隐式方法foreignKeyType在这里不适用,因为它在应用程序点之后,并且缺少显式结果类型
def test [T ^




您的代码如果您添加下限,则工作:



<$ p (T:null:

工作原理:

 阶> def test [T>:Null<:AnyRef](o:Option [T]):T = o getOrElse null; 
test:[T>:Null< ;: AnyRef](o:Option [T])T

scala>

scala>

scala>测试(无)
res0:空=空

scala> test(Some(Some))
res1:Some.type = Some


Ok, I know better than to use nulls as a design choice, but in this case I have to. Why the following does not compile?

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 is a subtype of all reference types, but the fact that T is a subtype of AnyRef doesn't guarantee that T is a reference type -- in particular, Nothing is a subtype of AnyRef which does not contain null.

Your code Works if you add a lower bound:

def test[T >:Null <:AnyRef](o :Option[T]) :T = o getOrElse null;

It works:

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

这篇关于null作为类型参数的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:41