Home

# Common methods for all sequences

The following methods are provided by all sequence classes, that is by String, StringBuilder, Array, ArrayBuffer, List, and ListBuffer.

When the result is again a sequence, it is of the same type as the original sequence. So the take method of arrays returns an array, while the take method of strings returns a string.

• A.length is the length (number of elements) of the sequence;
• A.isEmpty is the same as A.length == 0;
• A.nonEmpty is the same as A.length != 0;
• A.head the first element of the sequence;
• A.last the last element of the sequence;
• A.tail a copy of the sequence without its head;
• A contains x tests if the sequence contains an element equal to x;
• A take n returns a new sequence that has the first n elements of A;
• A drop n returns a new sequence that has the elements of A except for the first n elements;
• A.max, A.min, A.sum return the largest, smallest, and sum of elements in the sequence;
• A.reverse returns a new sequence with the elements of A in reverse order;
• A.sorted returns a new sequence with the elements of A in sorted order;
• A.mkString returns a string with all elements of A concatenated together;
• A mkString sep returns a string with all elements of A concatenated, using sep as a separator;
• A.mkString(start, sep, end) returns a string with all elements of A concatenated, using sep as a separator, prefixed by start and ended by end;
• A.toList returns a List with the same elements as the sequence.
• A.toArray returns an array with the same elements as the sequence.
• A.toSet returns a Set with the same elements as the sequence.
• A ++ B returns a new sequence that contains the elements of sequences A and B concatenated;
• A :+ el returns a new sequence that contains the elements of A with the element el appended at the back;
• el +: A returns a new sequence that contains the elements of A with the element el prepended at the front.

You can use a for-loop to look at the elements of a sequence one-by-one:

```scala> val L = List("CS109", "is", "the", "best")
L: List[java.lang.String] = List(CS109, is, the, best)
scala> for (i <- L)
|   println(i)
CS109
is
the
best
```
This is called "iterating over a sequence" and is quite similar to the for-loop in Python.