Scala中的Seq和List之间的区别 [英] Difference between a Seq and a List in Scala
问题描述
我在许多例子中看到有时候使用Seq,而其他时候是List ...
有什么区别,除了前一个是Scala类型,并且来自Java的列表?
在Java术语中,Scala的 Seq 将是Java的
。 List
,而Scala的 List
LinkedList
注意 Seq
是 trait
,这相当于Java的 interface
,但相当于即将到来的防御者方法。 Scala的 List
是一个通过 Nil
和 ::
,这是 List
的具体实现。
c> c>
$ b $除此之外,Scala的 List
是不可变的,而不是 LinkedList
。事实上,Java没有等价的不可变集合(只读的东西只保证新的对象不能改变,但你仍然可以改变旧的,因此,只读一个)。
Scala的列表
是由编译器和库高度优化的,它是函数式编程中的基本数据类型。然而,它有限制,它不足以并行编程。这些天,矢量
是比列表
更好的选择,但习惯很难打破。
Seq
是一个很好的泛化序列,所以如果你编程到接口,你应该使用。注意,其实有三个: collection.Seq
, collection.mutable.Seq
和 collection.immutable.Seq
,它是后面的一个是默认导入到范围。
还有 GenSeq
和 ParSeq
。后面的方法在可能的情况下并行运行,前者是 Seq
和 ParSeq
当代码的并行性无关紧要。他们都是相对新引进的,所以人们还没有使用它们。
I've seen in many examples that sometimes a Seq is being used, while other times is the List...
Is there any difference, other than the former one being a Scala type and the List coming from Java?
解决方案 In Java terms, Scala's Seq
would be Java's List
, and Scala's List
would be Java's LinkedList
.
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
.
So, where Java's List
is an interface
, Scala's List
is an implementation.
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'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
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.
There's also GenSeq
and ParSeq
. The latter methods run in parallel where possible, which the former is parent to Seq
and ParSeq
both, 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屋!