Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h2>Alternatives</h2> <p>Use <code>null</code> as a last resort. As already mentioned, <code>Option</code> replaces most usages of null. If you using <code>null</code> to implement deferred initialisation of a field with some expensive calculation, you should use a <code>lazy val</code>.</p> <h2>Canonical initialisation to null</h2> <p>That said, Scala does support <code>null</code>. I personally use it in combination with Spring Dependency Injection.</p> <p>Your code is perfectly valid. However, I suggest that you use <code>var t: T = _</code> to initialize <code>t</code> to it's default value. If <code>T</code> is a primitive, you get the default specific to the type. Otherwise you get <code>null</code>.</p> <p>Not only is this more concise, but it is necessary when you don't know in advance what <code>T</code> will be:</p> <pre><code>scala&gt; class A[T] { var t: T = _ } defined class A scala&gt; new A[String].t res0: String = null scala&gt; new A[Object].t res1: java.lang.Object = null scala&gt; new A[Int].t res2: Int = 0 scala&gt; new A[Byte].t res3: Byte = 0 scala&gt; new A[Boolean].t res4: Boolean = false scala&gt; new A[Any].t res5: Any = null </code></pre> <h2>Advanced</h2> <p>Using <code>var t: T= null</code> is a compile error if T is unbounded:</p> <pre><code>scala&gt; class A[T] { var t: T = null } &lt;console&gt;:5: error: type mismatch; found : Null(null) required: T class A[T] { var t: T = null } </code></pre> <p>You can add an implicit parameter as evidence that <code>T</code> is nullable -- a subtype of <code>AnyRef</code> not a subtype of <code>NotNull</code> This isn't fully <a href="https://stackoverflow.com/questions/2335496/how-does-the-notnull-trait-work-in-2-8-and-does-anyone-actually-use-it">baked</a>, even in Scala 2.8, so just consider it a curiousity for now. </p> <pre><code>scala&gt; class A[T](implicit ev: Null &lt;:&lt; T) { var t: T = null } defined class A </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload