I have two questions about nullable types in Scala:
Let's say I wish to define a new class: class myClass[T](x: T)
, and I'd like to make sure that T
is nullable. How do I do that?
I'd like to write a function def myFunc(x: T)
(not as part of the previous question), and I'd like to perform one thing if T
is nullable or another if not. The difference from the previous question is that here I don't wish to limit T
, but rather know if it's nullable or not. How do I do that?
1. Use a >: Null <: AnyRef
bound:
@ def f[T >: Null <: AnyRef](arg: T): T = arg
defined function f
@ f(10)
cmd3.sc:1: inferred type arguments [Any] do not conform to method f's type parameter bounds [T >: Null <: AnyRef]
val res3 = f(10)
^
cmd3.sc:1: type mismatch;
found : Int(10)
required: T
val res3 = f(10)
^
Compilation Failed
@ f("a")
res3: String = "a"
2. Use implicit type constraints with default values:
@ def isNullable[T](arg: T)(implicit sn: Null <:< T = null, sar: T <:< AnyRef = null): Boolean = sn != null && sar != null
defined function isNullable
@ isNullable(10)
res8: Boolean = false
@ isNullable("a")
res9: Boolean = true
These are similar to static type bounds, except that they are performed during implicit resolution instead of type checking and therefore permit failures if you provide default values for them (null
s in this case, no pun intended :))