Wednesday 12 August 2020

Scala: Mutable and Immutable variables

Variables in Scala are defined using either by the keyword ‘var’ or ‘val’. ‘val’ is equivalent to the final keyword in Java.

‘var’ is used to create mutable variables, whereas ‘val’ is used to create immutable variables.

 

Declaring a mutable variable

Syntax

var variable_name : Data_Type = value

 

Example

var principle : Integer = 100

scala> var principle : Integer = 100
var principle: Integer = 100

scala> principle = 123
// mutated principle

scala> print(principle)
123
scala> 

scala> principle = 555
// mutated principle

scala> print(principle)
555

Declaring an immutable variable

Syntax

val VARIBALE_NAME : Data_Type = value

 

Example

val PI : Double = 3.14

scala> val PI : Double = 3.14
val PI: Double = 3.14

scala> print(PI)
3.14

When you try to assign some value to this immutable variable PI, you will get an error.

scala> PI = 3.1428
          ^
       error: reassignment to val

Scala can infer the type from the value

Specifying type is optional, scala infers the type using the value assigned to the variable.

 

var name = "Krishna"

 

For example, from the above statement, Scala can infer the type of variable name as String.

scala> var a = 10
var a: Int = 10

scala> var name = "Krishna"
var name: String = Krishna

scala> var flag = true
var flag: Boolean = true




Previous                                                    Next                                                    Home

No comments:

Post a Comment