Introduction to Scala Part2 : Collections


Traversable : Element Retrieval

  • Operations: head, last, headOption, lastOption, and find.
  • Goal: select the first or last element of a collection, or else the first element matching a condition.

Note, however, that not all collections have a well-defined meaning of what “first” and “last” means.

For instance, a hash set might store elements according to their hash keys, which might change from run to run. In that case, the “first” element of a hash set could also be different for every run of a program.

A collection is ordered if it always yields its elements in the same order. Most collections are ordered, but some (e.g. hash sets) are not– dropping the ordering gives a little bit of extra efficiency.

Ordering is often essential to give reproducible tests and to help in debugging. That’s why Scala collections give ordered alternatives for all collection types. For instance, the ordered alternative for HashSet is LinkedHashSet.

> List(1,2,3).head
res0: Int = 1

> List(1,2,3).last
res1: Int = 3

(headOption and lastOption will be discussed in this course C#03)

Retrieve the Element of Index N
Create your playground on
This playground was created on, our hands-on, knowledge-sharing platform for developers.
Go to