How scala generic constraints to nullable types work

后端 未结 1 1930
挽巷
挽巷 2021-02-19 08:48

I\'ve tried two ways to constrain a generic type parameter to a nullable type, but both seem to have some unexpected problems.

First attempt (using T <: AnyRef):

相关标签:
1条回答
  • 2021-02-19 09:13
    def testAnyRefConstraint[T >: Null <: AnyRef](option:Option[T]):T = {
      option getOrElse null
    }
    

    I felt really stupid when I made this error the first time. Just because something extends AnyRef doesn't mean it must be nullable. For instance, Nothing is a subtype of AnyRef, and it is not nullable.

    The other way around is similar, because Any is a supertype of Null, and any Int is also an Any.

    0 讨论(0)
提交回复
热议问题