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

ScalaInitialization

Scala Problem Overview


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

Scala Solutions


Solution 1 - Scala

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.

Solution 2 - Scala

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGregor ScheidtView Question on Stackoverflow
Solution 1 - ScalaPaul ButcherView Answer on Stackoverflow
Solution 2 - ScalaChuckView Answer on Stackoverflow