1

I am learning from this site http://naildrivin5.com/scalatour/wiki_pages/ExplcitlyTypedSelfReferences/

trait BaseComponent {
    protected var label:Label = _
}

In this case what does the placeholder _ stands for?What would be the alternative?

MotaF
  • 605
  • 2
  • 9
  • 22
  • See http://stackoverflow.com/questions/8000903/what-are-all-the-uses-of-an-underscore-in-scala?s=1|2.3155 for other uses of `_`. – Alexey Romanov Jan 31 '17 at 14:26

1 Answers1

4

The placeholder syntax for a variable assings the default value to the variable. Assuming Label inherits AnyRef, that would be null.

The Scala language specification lays this out explicitly:

4.2 Variable Declarations and Definitions:

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                  |
Community
  • 1
  • 1
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321