val, lazy val, var ,def in Scala

val vs lazy val vs def

val : evaluates as soon as you initialise the object and stores the result.
lazy val : evaluates the first time that it’s accessed and stores the result.
def : executes the piece of code every time – pretty much like a Java method would.

val vs var

var is used in case you want that variable to be mutable. val is the other hand represents immutable variable whose value can not be changed once assigned.

Type Inference

When you assign an initial value to a variable, the Scala compiler can figure out the type of the varible based on the value assigned to it. This is called type inference. Therefore, you could write these variable declarations like this:

var myVar = 0
val myVal = 1

If, however, you did not assign an initial value to the variable, the compiler cannot figure out what type it is. Therefore, you have to explicitly specify the type if you do not assign an initial value to the variable. Here is how it looks:

var myVar :Int
val myVal :Int

Leave a Reply

Your email address will not be published. Required fields are marked *