Immutable Lists

Scala makes it easier and faster to access the first element of a list using the head method. Everything except the first element can be accessed using the tail method. Accessing the last element of the list requires traversing the list and so is more expensive than accessing the head and the tail. So, most operations on the list are structured around operations on the head and tail.

Let’s continue with the feeds example to learn about List. We can maintain an ordered collection of the feeds using a List:

 
val​ feeds = ​List​(​"blog.toolshed.com"​, ​"pragdave.me"​, ​"blog.agiledeveloper.com"​)

This creates an instance of List[String]. We can access the elements of the List using an index from 0 to list.length - 1. When we ...

Get Pragmatic Scala now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.