Generics scala对可空类型的泛型约束如何工作

Generics scala对可空类型的泛型约束如何工作,generics,scala,constraints,nullable,Generics,Scala,Constraints,Nullable,我尝试了两种方法将泛型类型参数约束为可为null的类型,但这两种方法似乎都存在一些意想不到的问题 第一次尝试(使用Tdef testAnyRefConstraint[T>:Null scala> def testAnyRefConstraint[T <: AnyRef](option:Option[T]):T = { | //without the cast, fails with compiler error: | // "found: Null(null

我尝试了两种方法将泛型类型参数约束为可为null的类型,但这两种方法似乎都存在一些意想不到的问题

第一次尝试(使用T
def testAnyRefConstraint[T>:Null
scala> def testAnyRefConstraint[T <: AnyRef](option:Option[T]):T = {
     | //without the cast, fails with compiler error:
     | //    "found: Null(null) required: T"
     | option getOrElse null.asInstanceOf[T]
     | }
testAnyRefConstraint: [T <: AnyRef](Option[T])T

scala> testAnyRefConstraint(Some(""))
res0: java.lang.String = 

scala> testAnyRefConstraint(Some(0))
<console>:16: error: inferred type arguments [Int] do not conform to method testAnyRefConstraint's type parameter bounds [T <: AnyRef]
       testAnyRefConstraint(Some(0))
scala> def testNullConstraint[T >: Null](option:Option[T]):T = {
     | option getOrElse null
     | }
testNullConstraint: [T >: Null](Option[T])T

scala> testNullConstraint(Some(""))
res2: java.lang.String = 

scala> testNullConstraint(Some(0))
res3: Any = 0
def testAnyRefConstraint[T >: Null <: AnyRef](option:Option[T]):T = {
  option getOrElse null
}