gpt4 book ai didi

kotlin - 为什么专家将 MutableList 更改为 List?

转载 作者:行者123 更新时间:2023-12-02 09:14:39 25 4
gpt4 key购买 nike

我问了一个问题 How to design a complex class which incude some classes to make expansion easily in future in Kotlin?关于如何设计一个复杂的类,其中包含一些类,以便将来在 Kotlin 中轻松扩展。

一位名叫 s1m0nw1 的专家给了我一个很好的答案,如下代码。

但不知道他为什么要换MutableListListhttps://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<DeviceDef>) {

inline fun <reified T> getDevice(): T {
return devices.filterIsInstance(T::class.java).first()
}
}

已添加

我认为 mutableListOf<DeviceDef>优于 ListOf<DeviceDef>以便日后扩展。

我可以用 aMutableList.add()当我附加 mutableListOf<DeviceDef> 的新元素时要扩展的函数.

如果我使用 ListOf<DeviceDef> , 我必须用 listOf(mBluetoothDef1, mWiFiDef1, //mOther) 来构建它, 这不好。对?
var aMutableList= mutableListOf<DeviceDef>()

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)

最佳答案

很抱歉没有首先给出解释。 docs 中解释了这些差异。 .:

Unlike many languages, Kotlin distinguishes between mutable and immutable collections (lists, sets, maps, etc). Precise control over exactly when collections can be edited is useful for eliminating bugs, and for designing good APIs.

It is important to understand up front the difference between a read-only view of a mutable collection, and an actually immutable collection. Both are easy to create, but the type system doesn't express the difference, so keeping track of that (if it's relevant) is up to you.

The Kotlin List<out T> type is an interface that provides read-only operations like size, get and so on. Like in Java, it inherits from Collection<T> and that in turn inherits from Iterable<T>. Methods that change the list are added by the MutableList<T> interface. [...]

List界面提供了只读 View ,因此您不能例如将新元素添加到列表中,这在多线程环境中具有许多优点。在某些情况下,您可能会使用 MutableList反而。
我还推荐以下讨论:
Kotlin and Immutable Collections?
编辑 (补充内容):
你可以做到这是一个单线没有任何 add调用:
val list = listOf(mBluetoothDef1, mWiFiDef1)

关于kotlin - 为什么专家将 MutableList 更改为 List?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48353232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com