top of page
Writer's pictureHarini Mallawaarachchi

Scala: Define variables

Compilers allocate memory and decide what can be stored in reserved memory based on variables' data types. As a result, you can store integers, decimals, or characters in variables by assigning different data types.


They can be defined as value. It is a variable that can change the value and this is called a mutable variable.

var myVar : String = "CodeXposer"

This means that it is a variable that cannot be changed and this is called an immutable variable.

val myVal : String = "CodeXposer"


Variable Data Types


val or var VariableName : DataType = [Initial Value]
var myVar :Int;
val myVal :String;

Variable Type Inference

By assigning a value to a variable, the Scala compiler can determine the variable's type. This is called variable type inference.

var myVar = 10;
val myVal = "CodeXposer";

Multiple assignments

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


Variable Scope

Depending on their use, Scala variables can have three different scopes.

  1. Fields - variables that belong to an object (can be defined by var or val)

  2. Method Parameters - used to pass the value inside a method, when the method is called. (defined by val keyword)

  3. Local Variables - variables declared inside a method (can be defined by var or val)




































0 views0 comments

Recent Posts

See All

Scala: For Loop

The for loop is an efficient way to write a loop that needs to be repeated a certain number of times. A for loop can be written in...

Comments


bottom of page