Scala

51 / 51
   

Scala - Variable Examples

Scala variables may or may not be any specific data type.

Scala allows variables to be defined in 2 ways - Immutable and mutable.

Immutable:
The value must be assigned at the time of declaring the variable whose value can not be changed later.
This type of variable is defined using val.
Example - val x = 5
Executing below to try to change the value of the variable will give an error.
x = 6

Mutable:
The value must be assigned at the time of declaring the variable but value can be changed later.
This type of variable is defined using var.
Example - var y = 9
Executing below to try to change the value of the variable will not give any error.
y = 10

More examples:

//without any data type
var x = 5

//with any data type of integer
var y:Int = 5

//with any data type of string
var z:String = "5"

//with any data type of char
var m:Char = 'a'

String literal has to be quoted in double quotes and single character has to be quoted in single quotes.

Multiple assignments

Scala supports multiple assignments. If a code block or method returns a Tuple (Tuple ? Holds collection of Objects of different types), the Tuple can be assigned to a val variable.

Example:

val (myVar1: Int, myVar2: String) = Pair(40, "Foo")