Ely*_*lye 5 mutable immutability kotlin
我们鼓励尽可能多地使用不可变变量.但是,如果我有时需要修改列表,我想知道我应该使用哪种方法......
val mutableList = mutableListOf()在那里我可以只add,remove因此要么
var immutableList = listOf()我+每次进行更改时都会创建一个新列表(使用过滤器或).我猜有一种不同的情景,一种比另一种更受欢迎.因此想知道何时应该使用其他等.
可变和不可变列表增加了模型的设计清晰度.
这是为了迫使开发人员思考和澄清收集的目的.
目的val和var不同于不可变和可变列表.
val和var关键字谈论如何处理变量的值/引用.
var - 可以在任何时间点更改分配给变量的值/引用.val - 值/引用只能为变量赋值一次,并且在执行后的某个时间点不能更改.在Kotlin中将可变列表分配给val并向其添加元素是完全有效的.
val a = mutableListOf(1,2,3,4)
a.add(5)
println(a)
Run Code Online (Sandbox Code Playgroud)
将输出
[1, 2, 3, 4, 5]
Run Code Online (Sandbox Code Playgroud)
val -> 你可能认为你不能为变量重新赋值。
//that is ok
var a:Int = 1
a=2
//Even you can reassign but you can't change its type
a= "string" //that's wrong
//that is wrong
val b:Int = 1
b = 2
Run Code Online (Sandbox Code Playgroud)
ListOf -> 你可能认为你不能插入/删除/更改列表中的任何元素(不能对列表的内容做任何事情)
var list:List<Int> = listOf(1,2,3,4) //[1,2,3,4]
//you can read list
list.get(0)
list[0]
//but you can't change(/write) the content of the list (insert/delete/alter)
list.set(0, 100)
list.add(5)
list.removeAt(0)
var mutableList:MutableList<Int> = mutableListOf(1,2,3,4) //[1,2,3,4]
//you can read and write
mutableList.get(0)
mutableList.set(0, 100) //[100,2,3,4]
mutableList.add(5) //[100,2,3,4,5]
mutableList.removeAt(0) //[2,3,4,5]
Run Code Online (Sandbox Code Playgroud)
所以结合他们两个,你会得到四个案例
情况 1:var mutableList:MutableList = mutableListOf(1,2,3,4)
//you can reassign
mutableList = mutableListOf(4,5,6,7) //[4,5,6,7]
//you can alter the content
mutableList.set(0, 100) //[100,5,6,7]
mutableList.add(8) //[100,5,6,7,8]
mutableList.removeAt(0) //[5,6,7,8]
Run Code Online (Sandbox Code Playgroud)
情况 2:val mutableList:MutableList = mutableListOf(1,2,3,4)
//you can't reassign
mutableList = mutableListOf(4,5,6,7) //that's wrong
//you can alter the content
mutableList.set(0, 100) //[100,2,3,4]
mutableList.add(8) //[100,2,3,4,8]
mutableList.removeAt(0) //[2,3,4,8]
Run Code Online (Sandbox Code Playgroud)
情况 3:var list:List = ListOf(1,2,3,4)
//you can reassign
list= ListOf(4,5,6,7) //[4,5,6,7]
//you can't alter the content
list.set(0, 100) //that's wrong
list.add(8) //that's wrong
list.removeAt(0) //that's wrong
Run Code Online (Sandbox Code Playgroud)
情况 4:val list:List = ListOf(1,2,3,4)
//you can't reassign
list= ListOf(4,5,6,7) //that's wrong
//you can't alter the content
list.set(0, 100) //that's wrong
list.add(8) //that's wrong
list.removeAt(0) //that's wrong
//the only thing you can do is Read
list.get(0) //return 1
list[0] //return 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1157 次 |
| 最近记录: |