Scala var vs val keyword

 341 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn about Scala var vs val keyword. This is one of the key and important concept of Scala and request you to please pay attention to it. Let you Scala journey begun 🙂

Scala var vs val

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

var a = "test"

var is a mutable variable which means it can be modified or changed.

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

val a = "test"

val is an immutable variable which means it cannot be modified or changed.

Please note ,we donot mentioned the type of the variable as Scala is intelligent enough infer the type!


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

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

Immutable variable(val), the value of val variable cannot be modified.

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

3. 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

Immutable variable(val) is like final keyword in Java.The type cannot be modified.


var examples

object StaticReference {

  def main(args: Array[String]) {

    //mutable int
    var x: Int = 1;

    x = 2;

    //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
  }
}

val examples

object StaticReference {

  def main(args: Array[String]) {

    //immutable int
    val x: Int = 1;

    x = 2;

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

    y = "xyz"

    //immutable Float
    val f: Float = 1.0f

    f = 2.0f

    //immutable Boolean
    val flag: Boolean = false;

    flag = true
  }
}

Hope this article helped you to understand Scala var vs val keyword. If you want to learn more about mutable and immutable variables and collections in Scala please refer below of my posts.

  1. Scala mutable and immutable variables
  2. 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!.