Anthony Accioly
Anthony Accioly

Reputation: 22461

Assign a underscore to a variable. What is the underscore doing?

Recently I've run into code like this:

var myVariable: variableKind = _

It seems to be a way to assign null to myVariable.

Can anyone explain the rationale behind _ in this case? What are the differences between assigning _ and null to a variable?

Upvotes: 5

Views: 687

Answers (2)

radumanolescu
radumanolescu

Reputation: 4161

The value assigned depends on the declared type. If your "variableKind" extends AnyRef, the default value (for any object) is null. For numeric types it's zero, etc.

Upvotes: 2

Lee
Lee

Reputation: 144106

It initialises the variable with it's default value - this value depends on the type. For numeric types, this is zero, false for booleans, () for Unit and null for types extending AnyRef.

Upvotes: 6

Related Questions