scala

Scala Journal : Initializing variables with underscore

Hey folks, this is going to be a short article, but an interesting one.
A lot of you, when using scala, might have declared and initialized the variables in scala using an underscore.

Never did that… probably you are a VAL Type personality.
But, if you ever did that… Congrats, you have used a special feature from Scala’s kitty .

What does using this underscore mean, when declaring variables ?
It simply means, you are assigning a default value to the variable during declaration, in programming world, we are just initializing the object (variable) with the default value.

Why would I care to do this ?
This will be only applicable, when you are declaring a VAR type variable, as for VAL, you need to initialize the variable at the same time of declaration, due to its immutable nature.
Supposedly, you just want to declare the variable and assign it some value based on program logic, I am sure, if you follow the code aesthetics, you would like to perform such declaration as the start of program, this is where assigning a default value comes into play.

Sample Assignment

// Declaring a String variable
var name : String = _

// Output
name: String = null

// Declaring a Int variable
var id : Int = _

//Output
id: Int = 0

What are the default values assigned ?
Refer to the below table.

  
Data TypeDefault Value
Int0
Long0L
Float0.0f
Double0.0d
Booleanfalse
Stringnull

If you did not know that simple fact, don’t worry….its normal…. even I got surprised after knowing this.
Keep learning……

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s