Skip to content
Search

Scala.collection

lastmod 2020-10-28created 2020-10-282 edits

Scala collections

Basics

Collections you will use all the time

Lists

A standard linked list.

scala> List(1, 2, 3)
res0: List[Int] = List(1, 2, 3)

As in other functional languages, you can build one with cons.

scala> 1 :: 2 :: 3 :: Nil
res1: List[Int] = List(1, 2, 3)

Sets

Duplicates are not allowed.

scala> Set(1, 1, 2)
res2: scala.collection.immutable.Set[Int] = Set(1, 2)

Sequences (Seq)

Sequences have an order.

scala> Seq(1, 1, 2)
res3: Seq[Int] = List(1, 1, 2)

Note that what is returned is a List. Seq is a trait. List is a good implementation of Seq. As you can see here, there is a factory object called Seq that creates Lists.

Maps (Map)

Maps store key-value pairs.

scala> Map('a' -> 1, 'b' -> 2)
res4: scala.collection.immutable.Map[Char,Int] = Map((a,1), (b,2))

Hierarchy

The following are all traits. The mutable and immutable packages each contain their own implementations of these traits.

Traversable

Every collection must be traversable. This trait defines the standard function combinators. These combinators are implemented on top of @foreach@. @foreach@ is a method every collection must implement.

Iterable

Returns the iterator() method, which returns an iterator that can loop over the elements.

Sequence (Seq)

An ordered sequence of items.

Set

A collection with no duplicate elements.

Map

A collection that holds key-value pairs.

See also

Favorite site

author Zer0 sitemap