Kotlin和不可变集合? [英] Kotlin and Immutable Collections?

查看:154
本文介绍了Kotlin和不可变集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Kotlin,并且看来我可能希望在明年使用它作为我的主要语言.但是,关于Kotlin是否具有不可变集合的研究一直在引起争议,我试图弄清楚是否需要使用Google Guava.

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.

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

Can someone please give me some guidance on this? Does it by default use Immutable collections? What operators return mutable or immutable collections? If not, are there plans to implement them?

推荐答案

科特林的 List 是只读的:

Kotlin's List from the standard library is readonly:

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

元素的一般有序集合.此界面中的方法 仅支持对列表的只读访问;读/写访问权限为 通过MutableList接口支持.

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.

参数
E-列表中包含的元素类型.

Parameters
E - the type of elements contained in the list.

如前所述,还有

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

一个通用的有序元素集合,支持添加和 删除元素.

A generic ordered collection of elements that supports adding and removing elements.

参数
E-列表中包含的元素类型.

Parameters
E - the type of elements contained in the list.

因此,Kotlin通过其接口强制执行只读行为,而不是像默认Java实现那样在运行时抛出异常.

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

同样,有一个MutableCollectionMutableIterableMutableIteratorMutableListIteratorMutableMapMutableSet,请参见

Likewise, there is a MutableCollection, MutableIterable, MutableIterator, MutableListIterator, MutableMap, and MutableSet, see the stdlib documentation.

这篇关于Kotlin和不可变集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆