kotlin var vs val

In Kotlin, var and val Both keywords are used for declaring variables.

var – Variable declare with var keywords are Mutable Variables, value of variable can be changed

fun main() {
    var color = "Green"
    color = "Red"
    println(color)
}
/** 
Output :
Red
*/

val – Variable declare with val keyword are Immutable Variables, this is read only variables. it’s not constant value. It is similar to final variable in Java.

fun main() {
    val pi: Double = 3.14
    val name: String = "Marsh"
    
    println("The value of pi is: $pi")
    println("My name is: $name")
    
    // Compilation error if you try to reassign a value to a val variable
    // pi = 3.14159
    // name = "Jane"
}

Output :

The value of pi is: 3.14
My name is: John

Use Cases:

  • Use var when you need a variable whose value may change during the execution of the program.
  • Use val when you want to declare a variable with a constant (unchangeable) value.

Leave a Reply