Gregor Scheidt
Gregor Scheidt

Reputation: 3982

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.

Upvotes: 132

Views: 28669

Answers (2)

Paul Butcher
Paul Butcher

Reputation: 10852

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

Upvotes: 161

Chuck
Chuck

Reputation: 237010

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.

Upvotes: 34

Related Questions