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.
// 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 Type||Default Value|
If you did not know that simple fact, don’t worry….its normal…. even I got surprised after knowing this.