scala list get element
To get an element from a Scala list, you can use the apply
method or the indexing syntax. Here are a few examples:
val myList = List(1, 2, 3, 4, 5)
// Using the apply method
val element1 = myList.apply(2) // Returns the element at index 2 (3 in this case)
// Using the indexing syntax
val element2 = myList(3) // Returns the element at index 3 (4 in this case)
In both cases, the index starts from 0, so myList(0)
will return the first element of the list. If the index is out of bounds, an IndexOutOfBoundsException
will be thrown.
You can also use the head
and tail
methods to get the first element and the rest of the list, respectively:
val firstElement = myList.head // Returns the first element of the list (1 in this case)
val restOfList = myList.tail // Returns the list without the first element (List(2, 3, 4, 5) in this case)
These methods are safe to use even with an empty list. If the list is empty, head
will throw a NoSuchElementException
, while tail
will return an empty list.
I hope this helps! Let me know if you have any further questions.