Question

var seq = Seq[String]()
seq = seq :+ "hello"

var set = Set[String]()
set += "hello"

what's the difference between Seq and Set?

Was it helpful?

Solution

Seq

http://www.scala-lang.org/api/current/scala/collection/Seq.html

Sequences always have a defined order of elements. Sequences provide a method apply for indexing.

Seq is similar to java.util.List.

Set

http://www.scala-lang.org/api/current/scala/collection/Set.html

A set is a collection that contains no duplicate elements.

This closely resembles a "set" in the mathematical sense: http://en.wikipedia.org/wiki/Set_(mathematics)

Set is similar to java.util.Set.

OTHER TIPS

This is described in many places, such as the documentation for Seq and Set and Scala's Collection Library guide.

One could also describe them by their characteristic functions:

  • A Set[A] is a function A => Boolean, which means one can check whether an element is present on it or not.

  • A Seq[A] is a function Int => A, which means that each element in it has an index, and one can retrieve the element that is at any given index.

This also explains the difference between the two statements:

seq = seq :+ "hello"
seq = "hello" +: seq 

set = set + "hello"

On a Set, one doesn't control the ordering of elements, so you simply add elements to it. On a Seq, because each element has an index, it is relevant where the element is being placed, and so we have +: and :+, which specify, respectively, that an element is to be prepended or appended to the sequence.

Asked myself this question and Scala worksheet provided an answer :

val seq = Seq(1,1)                   //> seq  : Seq[Int] = List(1, 1)
val set = Set(1,1)                   //> set  : scala.collection.immutable.Set[Int] = Set(1)

One noticeable difference is that Seq allows duplicates, while Set does not.

a set is a collection where you store distinct values while a seq is a more generalized version of collection its common superclass for some often used collections like Array,List etc..

in your example:

var set = Set[String]()
set += "hello"

set contains "hello"

set += "hello"

-> set remains unchanged.

for further information see the api on set : http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Set

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top