正如 Kotlin 文档所说,listOf<T>有三种实现:无参数、一个参数和可变参数。每个函数都应该返回 immutable List<T>。
val emptyList = listOf<String>()
val oneArgList = listOf("asd")
val varargsList = listOf("asd", "asd")
if (emptyList is MutableList) println("emptyList is mutable")
if (oneArgList is MutableList) println("oneArgList is mutable")
if (varargsList is MutableList) println("varargList is mutable")
Run Code Online (Sandbox Code Playgroud)
执行上面的代码导致
oneArgList is mutable
varargList is mutable
Run Code Online (Sandbox Code Playgroud)
为什么它会这样工作?这是理想的行为吗?
为什么会这样?
如果你查看源代码,你会发现它实际上创建了一个 Java ArrayList. 这利用了 JDK,而不必ArrayList在 Kotlin 中实现。MutableList请注意,即使成功,您的强制转换也是一种不好的编码实践,因为该listOf()函数已经指定它是 aList而不是 a MutableList。
emptyList()listOf()另一方面,(或) 使用EmptyList在 Kotlin 中实现的真正不可变的单例。
这是期望的行为吗?
其实没有。然而,它确实提供了一个不可变的接口。只要符合接口契约,支持数据结构的具体实现方式并不重要。作为程序员的你在使用的时候也应该遵守契约。
| 归档时间: |
|
| 查看次数: |
422 次 |
| 最近记录: |