353

多くの例で、Seq が使用されている場合もあれば、List が使用されている場合もあります...

前者が Scala 型であり、List が Java からのものである以外に違いはありますか?

4

5 に答える 5

469

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, 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.

于 2012-06-02T23:48:11.797 に答える
18

Scala では、 List は Seq から継承しますが、Productを実装します。Listの適切な定義は次のとおりです。

sealed abstract class List[+A] extends AbstractSeq[A] with Product with ...

[注:実際の定義は、Scala の非常に強力なコレクション フレームワークに適合して利用するために、もう少し複雑です。]

于 2012-06-02T23:21:52.563 に答える