Var str:String is mutable or immutable?


#1

Hi,

Is var str:String mutable or immutable?

As per document var is mutable…

But.


And String is immutable…

Please clarify contradiction.


#2

Val states that the reference is immutable, the value can not be reasigned:

val a : String = "hi" 
a = "b"  //not valid because a is reassigned

The variable which is referenced can change, depending on its implementation:

val a = mutableListOf<String>() //can change
val  b = listOf<String>()  //cannot change

The implementation of String is that it can’t change, so String itself is immutable.


#3

And to be quite precise val does not mean immutable, it means read-only. See https://www.google.com/amp/blog.danlew.net/2017/05/30/mutable-vals-in-kotlin/amp/