Search code examples
androidkotlinandroid-jetpack-composemutable

Why do we use val instead of var for remembering mutable state in Jetpack Compose?


I keep seeing sample codes written

val text = remember{ mutableStateOf("") }

When the string of the text changes, isn't the val a var? Hence the following line should also work? Definitely would like to prefer to understand why I can use val instead.

var text = remember{ mutableStateOf("") }

Solution

  • In kotlin, val used for declaring a reference which will not be able to repoint to another object. You can not change the reference but you can always change the state of pointed object.

    The changing string part is encapsulated in the object created by remember, not the text reference.

    val text = remember{ mutableStateOf("") }
    
    val myCar = Car() // object 578
    
    // changing the state of the car
    // but not the myCar
    myCar.setSpeed(100) 
    
    // compiler will not allow changing the reference
    // myCar = anotherCar
    
    var latestCar = Car() // object 345
    
    // latestCar refererence will point to object 578
    latestCar = myCar
    
    

    Kotlin's val is the equivalent of final keyword for references in java.