Scala 中 Seq 和 List 之间的区别 [英] Difference between a Seq and a List in Scala
问题描述
我在很多例子中看到,有时使用 Seq,而有时使用 List...
I've seen in many examples that sometimes a Seq is being used, while other times is the List...
除了前者是Scala类型和List来自Java之外,还有什么区别吗?
Is there any difference, other than the former one being a Scala type and the List coming from Java?
推荐答案
在 Java 术语中,Scala 的 Seq
将是 Java 的 List
,Scala 的 List
将是 Java 的 LinkedList
.
In Java terms, Scala's Seq
would be Java's List
, and Scala's List
would be Java's LinkedList
.
注意Seq
是一个trait
,相当于Java的interface
,但相当于新出现的防御者方法.Scala的List
是一个抽象类,由Nil
和::
扩展而成,是List
的具体实现.
Note that Seq
is a trait
, which is equivalent to Java's interface
, but with the equivalent of up-and-coming defender methods. Scala's List
is an abstract class that is extended by Nil
and ::
, which are the concrete implementations of List
.
所以,Java 的 List
是一个 interface
,Scala 的 List
是一个实现.
So, where Java's List
is an interface
, Scala's List
is an implementation.
除此之外,Scala 的List
是不可变的,而LinkedList
则不然.事实上,Java 并没有等价于不可变集合(只读的东西只能保证新对象不能改变,但你仍然可以改变旧对象,因此,只读"对象).
Beyond that, Scala's List
is immutable, which is not the case of LinkedList
. In fact, Java has no equivalent to immutable collections (the read only thing only guarantees the new object cannot be changed, but you still can change the old one, and, therefore, the "read only" one).
Scala 的 List
经过编译器和库的高度优化,是函数式编程中的基本数据类型.但是,它有局限性,不适合并行编程.现在,Vector
是比 List
更好的选择,但习惯很难改掉.
Scala's List
is highly optimized by compiler and libraries, and it's a fundamental data type in functional programming. However, it has limitations and it's inadequate for parallel programming. These days, Vector
is a better choice than List
, but habit is hard to break.
Seq
是对序列的一个很好的概括,所以如果你编程接口,你应该使用它.请注意,实际上有三个:collection.Seq
、collection.mutable.Seq
和 collection.immutable.Seq
,它是后一个是导入范围的默认".
Seq
is a good generalization for sequences, so if you program to interfaces, you should use that. Note that there are actually three of them: collection.Seq
, collection.mutable.Seq
and collection.immutable.Seq
, and it is the latter one that is the "default" imported into scope.
还有 GenSeq
和 ParSeq
.后一种方法在可能的情况下并行运行,而前一种方法是 Seq
和 ParSeq
的父级,这是一种适用于代码并行性无关紧要的概括.它们都是相对较新推出的,所以人们还没有使用它们.
There's also GenSeq
and ParSeq
. The latter methods run in parallel where possible, while the former is parent to both Seq
and ParSeq
, being a suitable generalization for when parallelism of a code doesn't matter. They are both relatively newly introduced, so people doesn't use them much yet.
这篇关于Scala 中 Seq 和 List 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!