为什么专家将MutableList更改为List?
我问了一个问题: 如何设计一个复杂的课程,包括一些课程,以便将来在Kotlin中轻松地进行扩展? 关于如何设计一个复杂的课程,包括一些课程,以便Kotlin将来可以轻松地扩展。
一位名叫s1m0nw1的专家给了我一个很好的答案,如下面的代码。
但我不知道他为什么要更改MutableList
到List
在https://stackoverflow.com/posts/47960036/revisions ,我可以得到正确的结果,当我使用MutableList。 你可以告诉我吗?
代码
interface DeviceDef data class BluetoothDef(val Status: Boolean = false) : DeviceDef data class WiFiDef(val Name: String, val Status: Boolean = false) : DeviceDef data class ScreenDef(val Name: String, val size: Long) : DeviceDef class MDetail(val _id: Long, val devices: List) { inline fun getDevice(): T { return devices.filterIsInstance(T::class.java).first() } }
添加
我认为mutableListOf
比ListOf
更好,以便将来扩展。
当我追加mutableListOf
新元素时,我可以使用aMutableList.add()
函数进行扩展。
如果我使用ListOf
,我必须使用listOf(mBluetoothDef1, mWiFiDef1, //mOther)
来构造它,但这并不好。 对?
var aMutableList= mutableListOf() var mBluetoothDef1= BluetoothDef(true) var mWiFiDef1= WiFiHelper(this).getWiFiDefFromSystem() aMutableList.add(mBluetoothDef1) aMutableList.add(mWiFiDef1) // aMutableList.add(mOther) //This is extension var aMDetail1= MDetail(myID, aMutableList)
对不起,没有给出解释。 文档中解释了这些差异。
与许多语言不同,Kotlin区分了可变集合和不可变集合(列表,集合,映射等)。 精确控制集合何时编辑对于消除错误和设计良好的API非常有用。
了解可变集合的只读视图和实际不可变集合之间的区别是非常重要的。 两者都很容易创建,但types系统并没有表现出差异,所以跟踪(如果相关)是由你决定的。
Kotlin
List
types是一个接口,提供只读操作,如大小,获取等。 像在Java中一样,它inheritance自Collection
,继而从Iterable
inheritance。 改变列表的方法由MutableList
接口添加。 […]
List
接口提供了一个只读视图,所以你不能在列表中添加新元素,例如在multithreading环境中有很多优点。 可能会出现你将使用MutableList
。
我也推荐以下讨论: Kotlin和不可变集合?
编辑 (新增内容):
你可以这样做,是一个没有任何add
调用的单线程:
val list = listOf(mBluetoothDef1, mWiFiDef1)