我不断看到编写的示例代码
val text = remember{ mutableStateOf("") }
当文本字符串改变时,val
不就是var
吗?因此以下行也应该有效?绝对想了解为什么我可以使用 val
代替。
var text = remember{ mutableStateOf("") }
最佳答案
在 Kotlin 中,
val
用于声明不能重新指向另一个对象的引用。
您无法更改引用,但始终可以更改指向对象的状态。
变化的字符串部分封装在由remember创建的对象中,而不是text
引用中。
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 的 val
相当于 Java 中引用的 final
关键字。
关于android - 为什么我们使用 val 而不是 var 来记住 Jetpack Compose 中的可变状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71529740/