JAVA DEVELOPER SITE
 

Scala - Variables


Assigning different data types to variables, you can store integers, decimals, or characters in these variables.

Variable Declaration

Scala has a different syntax for declaring variables. myVar is declared using the keyword var. It is a variable that can change value and this is called mutable variable. Following is the syntax to define a variable using var keyword
var myVar : String = "JoJo"
myVal is declared using the keyword val. This means that it is a variable that cannot be changed and this is called immutable variable Following is the syntax to define a variable using val keyword

Syntaxt

val myVal : String = "JoJo"

Variable Data Types

The type of a variable is specified after the variable name and before equals sign

Syntax

val or val VariableName : DataType = [Initial Value]

Syntax

var myVar :Int;
val myVal :String;

Variable Type Inference

initial value to a variable, the Scala compiler can figure out the type of the variable based on the value assigned to it.
var myVar = 12;
val myVal = "Hello, Scala!";

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.
val (myVar1: Int, myVar2: String) = Pair(10, "JoJo")
the type inference gets it right

Syntax


val (myVar1, myVar2) = Pair(10, "JoJo")