Variables in Scala

Variables in Scala can be either mutable or immutable.

TypeDescription
valImmutable
varMutable

It is preferrable to use val over var unless you are sure that the variable's value could change after declaration.

Immutable val

 object UsingVal {   def main(args: Array[String]) = {     val msg = "You cannot change this.";     msg = "You cannot tell me what to do!";     // Throws an error because you cannot reassign a `val`   } }

Mutable var

 object UsingVal {   def main(args: Array[String]) = {     val msg = "You can change this.";     msg = "Ok.";     // Compiles without an error.   } }
Table Of Contents