gpt4 book ai didi

kotlin - listOf Kotlin 返回的对象类型

转载 作者:行者123 更新时间:2023-12-02 12:01:07 26 4
gpt4 key购买 nike

正如 Kotlin 文档所说 listOf<T>具有三种实现:无参数、一个参数和可变参数。每个函数都应该返回不可变 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")

执行上述代码会导致
oneArgList is mutable
varargList is mutable

为什么它会这样工作?这是期望的行为吗?

最佳答案

Why it works that way?



如果您查看源代码,您会发现它实际上创建了一个 Java ArrayList .这利用了 JDK 而不必实现 ArrayList在 Kotlin 。请注意,您的类型转换 MutableList即使从 listOf() 开始成功,也是一种不好的编码习惯。函数已经指定它是 List而不是 MutableList .
emptyList() (或 listOf() )另一方面使用 EmptyList在 Kotlin 中实现的单例是真正不可变的。

Is this desired behaviour?



其实没有。然而,它确实可以呈现一个不可变的接口(interface)。只要符合接口(interface)契约,支持数据结构的实现方式并不重要。作为程序员,您在使用它时也应该遵守契约(Contract)。

关于kotlin - listOf Kotlin 返回的对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60382150/

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