27 List

 

After reading this lesson, you will be able to

  • Define an ordered sequence of items
  • Adding elements to an existing list
  • Traverse and transform its items using pattern matching

Now that you have discovered the Option type in the previous unit, you’ll learn about List in this lesson; many of the concepts you have mastered for optional values are also applicable to lists but in a slightly different context. The type List allows you to represent an immutable ordered sequence of elements. This concept is not exclusive to the Scala language. For example, you use an ArrayList or a LinkedList in Java, a list in C++, a list literal in Python, and an array in Javascript. You’ll find that lists in Scala are relatively similar to many other languages, with a fundamental difference: they are immutable by default. Using mutable lists is still possible but discouraged. In this lesson, you’ll learn how to create a list and add elements to it. You’ll also see how to pattern match on lists. In the capstone, you’ll use lists to represent the information presented in the movies data set.

27.1 Creating a list

Imagine you want to write a program to keep track of your contacts. You could present your data using a list data structure.

27.2 Adding elements to a list

27.3 Pattern matching on a list

Summary

Answers to quick checks