Scala mutable and immutable variables

 357 total views,  2 views today

Welcome to Scala series.  In this tutorial, you will learn about Scala mutable and immutable variables. This is one of import and key feature of Scala. So please learn this basics to start you Scala journey.

Scala mutable and immutable variables

Mutable variables

What is mutable? – A data defined as mutable can be changed whenever it is required. So in Scala, to defined a data as a mutable we use “var” keyword.

var keyword is used to mark the variable as mutable.E.g.,

var a = "test"

Mutable variable(var) can be modified with new value.

a = "apple" // we can modify the mutable variable

Mutable variable(var) type cannot be changed once it is initialized.

a = 10 // This will throw compilation error stating that type mismatch. Because a is already assigned a value as String

var examples

 def main(args: Array[String]) {

    //mutable int
    var x: Int = 1;

    x = 2; //modifying the value

    //mutable String
    var y: String = "abc"

    y = "xyz"

    //mutable Float
    var f: Float = 1.0f

    f = 2.0f

    //mutable Boolean
    var flag: Boolean = false;

    flag = true
  }
}

Immutable variable

What is immutable? – A data defined as immutable cannot be modified or changed. So in Scala, to defined a data as an immutable we use “val” keyword.

val keyword is used to mark the variable as immutable.E.g.,

val a = "test"

Once a variable is marked as val, the value of val variable cannot be modified.

a = "sample" // This will throw compilation error stating that reassignment to val.

val is like final keyword in Java

val examples

object StaticReference {

  def main(args: Array[String]) {

    //immutable int
    val x: Int = 1;

    x = 2; // compilation error  - Reassignment to val

    //immutable String
    val y: String = "abc"

    y = "xyz" // compilation error  - Reassignment to val

    //immutable Float
    val f: Float = 1.0f

    f = 2.0f // compilation error  - Reassignment to val

    //immutable Boolean
    val flag: Boolean = false;

    flag = true // compilation error  - Reassignment to val
  }
}

Hope this article helped you to understand scala mutable and immutable variables.

if you want to learn more about mutable and immutable collections of Scala, I have written a separate post on that. Please check Scala mutable and immutable collections.

References Official documentation

Please leave a comment and give us a thumbs up.

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.