Variables in Scala
Variables in Scala can be either mutable or immutable.
Type | Description |
---|---|
val | Immutable |
var | Mutable |
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 UsingVar { def main(args: Array[String]) = { var msg = "You can change this."; msg = "Ok."; // Compiles without an error. } }
Table of Contents