DEV Community

loizenai
loizenai

Posted on

Kotlin mutable & immutable variable – Val vs Var

https://grokonez.com/kotlin/kotlin-mutable-immutable-variable-val-vs-var

Kotlin mutable & immutable variable – Val vs Var

In the tutorial, JavaSampleApproach explains the differences between Kotlin Val vs Var.

1. Kotlin Val

val is used to declare a read-only variable. It likes final in Java.
So we can NOT re-assign a new value for val variable.

kotlin val vs var - val

2. Kotlin Var

var is used to declare a mutable variable. So we can change value of var variables.


data class Customer(val id: Int, var name: String)

fun main(args : Array) {
    /*
     * I. Basic Datatype
     */
    var a = 5
    println("a = $a") // a = 5
    // can not re-assign a new value
    a = 6
    println("a = $a") // a = 6
    
    var str = "abc"
    println("str = $str") // str = abc
    // can not re-assign a new value
    str = "xyz"
    println("str = $str") // str = xyz
    
    /*
     * II. Object data model
     */
    var cust = Customer(1, "Jack")
    println("cust = $cust") // cust = Customer(id=1, name=Jack)
    // can not re-assign a new value
    cust = Customer(2, "Mary")
    println("cust = $cust") // cust = Customer(id=2, name=Mary)
}

3. Kotlin Val & Var with Object's Properties

More at:

https://grokonez.com/kotlin/kotlin-mutable-immutable-variable-val-vs-var

Kotlin mutable & immutable variable – Val vs Var

Top comments (0)