Scala 集合不一致 [英] Scala Collections inconsistencies

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

问题描述

为什么 Scala Collections API 中的 Sets 和 Lists 之间缺乏一致性?

Why is there a lack of consistency between Sets and Lists in Scala Collections API?

比如有不可变的Set,也有可变的.如果我想使用后者,我可以简单地这样做:

For example, there is immutable Set, but also a mutable one. If I want to use the latter, I can simply do this:

val set = Set[A]()
set += new A

然而,本质上没有可变列表.如果我想使用 Lists 编写类似的代码片段,该使用哪种数据结构?LinkedList 听起来是一个不错的候选者,因为它是可变的,但没有定义 += 方法.ListBuffer 似乎满足要求,但它不是一个列表.

However, there is no mutable List, per se. If I want to write a similar code snippet using Lists, which data structure to use? LinkedList sounds as a good candidate, because it is mutable, but has no += method defined. ListBuffer seems to satisfy the requirements, but it is not a list.

阅读 2.8 Collections 文档后,我得出结论 MutableList 可能是最合适的.

After reading 2.8 Collections docs I come to the conclusion MutableList is probably the best fit.

我仍然希望有 scala.collection.mutable.List.

I still somehow wish there was scala.collection.mutable.List.

推荐答案

这样做的原因是 Java 选择了 functional List 类型来表示某些东西它不是(即 java.util.List 不是 list).

The reason for this is that Java has co-opted the functional List type to mean something that it is not (i.e. java.util.List is not a list).

对于函数式编程语言来说,拥有 mutable List 可能没有意义,因为这样的类型是矛盾的.因此ListBufferArrayBuffer.或者直接使用IndexedSeq,其中有可变和不可变的实现

It probably makes no sense for a functional programming language to have a mutable List as such a type is an oxymoron. Hence ListBuffer or ArrayBuffer. Or just use IndexedSeq, of which there are mutable and immutable implementations

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

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