131

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

Chuck
  • 234,037
  • 30
  • 302
  • 389
Gregor Scheidt
  • 3,952
  • 4
  • 24
  • 28

2 Answers2

159

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. From the Scala Language Specification:

0 if T is Int or one of its subrange types,
0L if T is Long,
0.0f if T is Float,
0.0d if T is Double,
false if T is Boolean,
() if T is Unit,
null for all other types T.

Paul Butcher
  • 10,722
  • 3
  • 40
  • 44
  • 7
    Ha, nice catch on the val/var switch. My brain just skimmed right past it. – Chuck Dec 01 '11 at 17:56
  • 2
    Any insight into why this hasn't been made to work with `val`? – Erik Kaplun Jan 28 '14 at 23:06
  • 4
    @ErikAllik: This is pure speculation, but `val a: Int = _` is probably a compilation error because it would be bad practice if it worked. It would just be an obfuscated way of writing `val a: Int = 0`. Setting a `var` to a default value makes sense since a `var` is expected to change, but a `val` is fixed so best practice would be to assign a value explicitly. – Shuklaswag Jul 09 '16 at 20:43
  • 1
    @Shuklaswag: Only if you know its an integer. I'm trying to use this to initialise a val of a type that I don't know yet. – Adrian May Apr 12 '17 at 22:02
34

It initializes a to the default value of the type A. For example, the default value of an Int is 0 and the default value of a reference type is null.

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • 10
    What is the default value of a class that mixes in the `NotNull` trait? :-) – Jean-Philippe Pellet Dec 01 '11 at 08:39
  • 11
    @Jean-PhilippePellet: As of Scala 2.9.0.1 (which is the most recent version I've used), the default value of a class that mixes in the NotNull trait is — dramatic pause — **null**. I expect this will probably change at some point, but currently it seems `_` trumps `NotNull`. – Chuck Dec 01 '11 at 17:53