In this tutorial, we’ll discuss various ways of accessing the items of a List by index in Scala.
2. Getting an Item Based on Index
The class List provides various methods to access its elements based on the index. Let’s explore these methods one by one:
Let’s define a List of integers:
val numbers = List.range(1, 10); // List(1, 2, 3, 4, 5, 6, 7, 8, 9)
The apply() method gets the List item based on the index provided:
assert(numbers.apply(5) == 6)
Here, 6 is present at index 5 in numbers.
However, we must keep in mind that it throws an IndexOutOfBoundsException if the index provided is outside the range.
The method lift() provides a “null-aware” result as it returns a value of type Option. The class Option has two types of instances, Some and None.
This means that if the item is present at the specified index, we get the Optional type Some. Otherwise, we get the Optional type None:
var option = numbers.lift(1) // returns Some assert(option.isDefined) assert(option.get == 2) option = numbers.lift(10) // returns None assert(option.isEmpty)
Here, passing index as 1 to lift() returns an Optional type Some containing value 2. Whereas there’s no element present at index 10. Therefore, we get an Optional type None, which is empty.
Subsequently, we can perform various functional operations on the returned Optional value.
However, we must remember that invoking the get() method on an instance of type None throws a NoSuchElementException.
In Scala, we have a general rule for applying parenthesis surrounding one or more values to a variable. The rule is such that Scala transforms the parenthesis to the invocation of the apply() method on that variable.
Let’s see an example:
assert(numbers(8) == 9)
In the above code, Scala internally transforms numbers(8) to numbers.apply(8). Therefore, we get the value 9 present at index 8 in numbers.
So, these two statements are actually equivalent:
scala> println(numbers(8)) 9 scala> println(numbers.apply(8)) 9
However, we must note that the transformation happens because the class List actually defines the method apply() in it.
Finally, similar to apply(), in this case also, accessing an element beyond the range will throw an IndexOutOfBoundsException.
3. List.head() and List.last()
We can use the head() and last() methods of the class List to get the first and last elements respectively.
The method head() returns the first item of the list:
assert(numbers.head == 1)
Similarly, we can use the method last() to get the last item on the list:
assert(numbers.last == 9)
Here, 1 and 9 are the first and last items on our list.
In this article, we discussed various methods to get the list items by index in Scala.
As always, the full source code for the examples can be found over on GitHub.