Kotlin编辑清单 [英] Kotlin Editing List

查看:72
本文介绍了Kotlin编辑清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin中编辑不变的List的最佳方法是什么?

What is the best way to edit an immutable List in Kotlin?

我知道List实际上不是不变的,但是如果我要将List传递到函数中,并且我需要整个列表减去单个元素,是否有支持的方法来处理?如果我希望整个列表都包含一个附加元素怎么办?

I understand that List is not actually immutable, but if I'm passing a List into into a function and I need that entire list minus a single element, is there a supported way to handle that? What about if I want that entire list with an additional element?

推荐答案

如果您自己创建列表,则可以调用mutableListOf("foo", "bar")来获取MutableList的实例,而不是调用listOf("foo", "bar").

If you are creating the list yourself, instead of calling listOf("foo", "bar") call mutableListOf("foo", "bar") to get an instance of a MutableList.

如果您获得列表,例如作为方法的参数,请在其上调用toMutableList()以获取可变的副本.

If you get the list, e.g. as a parameter to a method, call toMutableList() on it to get a mutable copy.

或者使用许多内置扩展方法之一,例如map()filter(),以获取带有已修改元素的 new 列表.例如,要获取没有前n个元素的列表,请使用drop(n).要仅获取前n个元素,请调用take(n). 此处,您可以找到更多内置扩展方法.

Alternatively use one of the many built-in extension methods like map() or filter() to get a new list with the modifed elements. For example, to get a list without the first n elements use drop(n). To get only the first n elements call take(n). Here you can find more of the built-in extension methods.

如果您需要加入两个列表,只需使用加号运算符:val newList = list1 + list2.

If you need to join two lists, just use the plus operator like this: val newList = list1 + list2.

请注意,修改作为方法参数的列表可能是代码的味道.这就是为什么所有内置方法都返回副本的原因.还有你的假设

Note, that modifying lists that are parameters to your methods can be a code smell. That's why all the built-in methods return copies. Also your asumption

我知道List实际上并不是一成不变的

I understand that List is not actually immutable

是错误的.如您所见此处,如果您不带参数调用listOf(),则标准库将返回一个不变的空列表.

is wrong. As you can see here, the standard library will return an immutable empty list if you call listOf() without arguments.

在Java中,默认情况下List接口是可变的,当您尝试修改不可变列表(例如通过调用Arrays.asList()创建的不可变列表)时,这会导致异常.因此,在科特林,情况恰恰相反.

In Java the List interface is mutable per default which can lead to exceptions when you try to modify an immutable list such as one that was created by calling Arrays.asList(). That's why in Kotlin the opposite is the case.

这篇关于Kotlin编辑清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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