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

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

问题描述

我正在学习 Kotlin,看起来我可能想在明年将其用作我的主要语言.但是,我不断收到相互矛盾的研究,即 Kotlin 是否具有不可变集合,我试图弄清楚是否需要使用 Google Guava.

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

解决方案

Kotlin 的 List 来自标准库是只读的:

interface List:集合<E>(来源)

<块引用>

元素的通用有序集合.此接口中的方法仅支持对列表的只读访问;读/写访问是通过 MutableList 接口支持.

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

如前所述,还有MutableList

interface MutableList:列表<E>,MutableCollection<E>(来源)

<块引用>

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

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

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

同样,还有一个 MutableCollectionMutableIterableMutableIteratorMutableListIteratorMutableMapMutableSet,请参阅 stdlib 文档.

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?

解决方案

Kotlin's List from the standard library is readonly:

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
E - the type of elements contained in the list.

As mentioned, there is also the MutableList

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

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

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

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

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

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

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