为什么val不影响KOTLIN中的数组?

时间:2019-06-06 07:49:38

标签: arrays kotlin

fun main(args:Array<String>)
{
    val num:Int=6
    //  num=10 if I initialize like this it will error
    val arr=Array<Int>(5){0}
    arr[0]=5  //when I initialize like this it not error 
}

//请告诉我为什么它不是错误

1 个答案:

答案 0 :(得分:4)

在Kotlin中,arr表示“只读”,即不会生成该属性的设置器。这意味着您无法重新分配val readOnly = arrayListOf<Int>() readOnly.add(1) // OK readOnly = arrayListOf() // compilation error val immutable = Collections.unmodifiableList(arrayListOf(1)) immutable[0] = 2 // throws exception at runtime val anotherImmutable = listOf(1) anotherImmutable[0] = 2 // compilation error ,但仍可以更改其内容。

这是不变性(您将无法更改数组内容)和只读(您无法重新分配变量)之间的区别。

示例:

.ipynb
相关问题