25 Tuple and Unapply
After reading this lesson, you’ll be able to:
- Group elements using tuples
- Retrieve data from tuples
- Extract information from an instance of a class using the unapply method
In the previous lessons, you have discovered how to handle nullable values using the type Option. In this lesson, you’ll learn about tuples, one of the most basic data structures that Scala offers to quickly group data in a given order. You’ll then combine what you have seen about tuples and the type Option to discuss the unapply method. The function unapply is complementary to apply: you use the apply function to create a class instance and unapply to extract information from it. Pattern matching is one of the most powerful tools you can use. So far, you have seen that you can pattern match over raw values (e.g., string, integers, doubles), objects, and case classes. By defining an unapply method for a class, you’ll also be able to pattern match on them. In the capstone, you’ll use tuples to group data together, and you’ll define unapply methods to pattern match over classes without exposing sensitive information.