Alternatives
Use null as a last resort. As already mentioned, Option replaces most uses of null. If you use null to implement deferred field initialization with some expensive calculation, you should use lazy val .
Canonical initialization to zero
However, Scala supports null . I personally use it in combination with Spring Injection of Dependency.
Your code works fine. However, I suggest you use var t: T = _ to initialize t its default value. If t is primitive, you get a default value that matches the type. Otherwise, you will get null .
Not only is this more concise, but necessary when you do not know in advance what t will be:
scala> class A[T] { var t: T = _ } defined class A scala> new A[String].t res0: String = null scala> new A[Object].t res1: java.lang.Object = null scala> new A[Int].t res2: Int = 0 scala> new A[Byte].t res3: Byte = 0 scala> new A[Boolean].t res4: Boolean = false scala> new A[Any].t res5: Any = null
Additionally
Using var t: T= null is a compilation error if T is unlimited:
scala> class A[T] { var t: T = null } <console>:5: error: type mismatch; found : Null(null) required: T class A[T] { var t: T = null }
You can add an implicit parameter as evidence that t is NULL - the AnyRef subtype AnyRef not a NotNull subtype It's not completely baked , even in Scala 2.8, so just think about it now.
scala> class A[T](implicit ev: Null <:< T) { var t: T = null } defined class A
retronym Mar 13 2018-10-13T00: 00Z
source share