I am learning Kotlin and it is looking likely I may want to use it as my primary language within the next year. However, I keep getting conflicting research that Kotlin does or does not have immutable collections and I'm trying to figure out if I need to use Google Guava.

有人能给我一些指导吗?它默认使用不可变集合吗?哪些运算符返回可变或不可变集合?如果没有,是否有实施计划?

推荐答案

标准库中的Kotlin的List是只读的:

interface List<out E> : Collection<E> (source)

A generic ordered collection of elements. Methods in this interface support only read-only access to the list; read/write access is supported through the MutableList interface.

Parameters

正如前面提到的,还有MutableList

interface MutableList<E> : List<E>, MutableCollection<E> (source)

支持添加和的元素的通用有序集合 正在删除元素.

Parameters

Due to this, Kotlin enforces readonly behaviour through its interfaces, instead of throwing Exceptions on runtime like default Java implementations do.

同样,还有MutableCollectionMutableIterableMutableIteratorMutableListIteratorMutableMapMutableSet,请参见stdlib文档.

Kotlin相关问答推荐

解决Microronaut中多个可能的Bean候选者冲突

在Jetpack Compose中创建波浪式文本动画:顺序中断问题

如何进行基于lambda/谓词的两个列表的交集?

KTOR';S函数`staticResources`在Kotlin本机目标上不可用

找不到有效的 Docker 环境

为什么记得不将 StateFlow 转换为特定类型?

如何避免键盘打开时jetpack compose 内容上升

mutableStateOf 在 Jetpack Compose 中不记住 API 的情况下保持重组后的值

在jetpack compose中将默认方向设置为横向?

在 Kotlin 中 import 如何找到文件路径?

PRDownloader 即使在实现库后也无法工作.未知参考:Android Studio 中的 PRDownloader

有没有办法重用 Job 实例?

对列表中数字的子集求和

Kotlinwhen表达式在使用主题时是否支持复合布尔表达式?

将 jetpack compose 添加到现有元素

Foo::class.java 和 Foo::javaClass 有什么区别?

从命令行运行Java到Kotlin转换器?

使用 Moshi/Retrofit2 访问深度嵌套的 JSON 数组

从 Kotlin 访问 Integer.class

如何在 Kotlin 中定义新的运算符?