What is the difference between a var and val definition in Scala?

Viewed 125326

What is the difference between a var and val definition in Scala and why does the language need both? Why would you choose a val over a var and vice versa?

13 Answers

Val means its final, cannot be reassigned

Whereas, Var can be reassigned later.

Though many have already answered the difference between Val and var. But one point to notice is that val is not exactly like final keyword.

We can change the value of val using recursion but we can never change value of final. Final is more constant than Val.

def factorial(num: Int): Int = {
 if(num == 0) 1
 else factorial(num - 1) * num
}

Method parameters are by default val and at every call value is being changed.

In terms of javascript , it same as

val -> const var -> var

Related