Scala var vs val keyword

 247 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn about Scala var vs val keyword.

Scala var vs val

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

var a = "test"

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

val a = "test"

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

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

5 thoughts on “Scala var vs val keyword

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.