官术网_书友最值得收藏!

  • Functional Kotlin
  • Mario Arias Rivu Chakraborty
  • 266字
  • 2021-06-24 19:15:28

Immutable reference  (referential immutability)

Referential immutability enforces that, once a reference is assigned, it can't be assigned to something else. Think of having it as a val property of a custom class, or even MutableList or MutableMap; after you initialize the property, you cannot reference something else from that property, except the underlying value from the object. For example, take the following program:

class MutableObj { 
    var value = "" 
 
    override fun toString(): String { 
        return "MutableObj(value='$value')" 
    } 
} 
 
fun main(args: Array<String>) { 
    val mutableObj:MutableObj = MutableObj()//(1) 
    println("MutableObj $mutableObj") 
    mutableObj.value = "Changed"http://(2) 
    println("MutableObj $mutableObj") 
 
    val list = mutableListOf("a","b","c","d","e")//(3) 
    println(list) 
    list.add("f")//(4) 
    println(list) 
} 

Have a look at the output before we proceed with explaining the program:

So, in this program we've two val properties—list and mutableObj. We initialized mutableObj with the default constructor of MutableObj, since it's a val property it'll always refer to that specific object; but, if you concentrate on comment (2), we changed the value property of mutableObj, as the value property of the MutableObj class is mutable (var).

It's the same with the list property, we can add items to the list after initialization, changing its underlying value. Both list and mutableObj are perfect examples of immutable reference; once initialized, the properties can't be assigned to something else, but their underlying values can be changed (you can refer the output). The reason behind that is the data type we used to assign to those properties. Both the MutableObj class and the MutableList<String> data structures are mutable themselves, so we cannot restrict value changes for their instances.

主站蜘蛛池模板: 息烽县| 莱西市| 梁山县| 门头沟区| 房产| 盐山县| 梁河县| 福建省| 河东区| 张家界市| 红安县| 福海县| 林芝县| 明光市| 紫阳县| 平陆县| 成都市| 行唐县| 宁德市| 正安县| 宁夏| 太原市| 镇平县| 东辽县| 阳新县| 南充市| 鞍山市| 安阳市| 南乐县| 咸丰县| 瑞安市| 青田县| 榆树市| 龙南县| 商丘市| 南阳市| 滦平县| 江华| 宝清县| 牙克石市| 徐州市|