scalainitialization

In Scala, what exactly does 'val a: A = _' (underscore) mean?


What exactly does val a: A = _ initialize a value to? Is this a typed null? Thanks.


Solution

  • val a: A = _ is a compile error. For example:

    scala> val a: String = _
    <console>:1: error: unbound placeholder parameter
           val a: String = _
                           ^
    

    What does work is var a: A = _ (note var instead of val). As Chuck says in his answer, this initialises the variable to a default value based on its type.

    From the Scala Language Specification:

    A variable definition var x: T = _ can appear only as a member of a template. It introduces a mutable field with type T and a default initial value. The default value depends on the type T as follows:

    default type T
    0 Int or one of its subrange types
    0L Long
    0.0f Float
    0.0d Double
    false Boolean
    () Unit
    null all other types