Lesson 25 Tuple and Unapply
After reading this lesson, you will 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 will learn about tuples, one of the most basic data structures that Scala has to offer to quickly group data in a given order. You will then combine what you have seen about tuples and Option to discuss the unapply method. The function unapply is complementary to apply: while you can use apply to create an instance of a class, unapply allows you 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 will also be able to pattern match on them. In the capstone, you will use tuples to group data together, and you will define unapply methods to pattern match over classes without exposing sensitive information.