If the optional value is absent, it returns None without applying any function f.Ĭonsider the case class Car shown in listing 1. If the optional value is present, map applies the function f to it and wraps the result in a Some instance. Figure 1 provides a summary of how the high order function map operates on an instance of Option.įigure 1: Visual representation of the map operation on Option. You don’t need to remember what a map function does, and you need to look at its signature: if you have an instance of Option and you have a function f that transforms an A into a B, then you know how to obtain a value of type Option through to the map function. # A “this” is a keyword that refers to the current instance of the class.Ĭompare the implementation of map with your implementation of the function ownerName using pattern matching: they’re similar and have the same structure! Let’s have another look at the signature of the map function for the abstract class Option: For a quick intro to Option, check out part 1. In part 3, you’re going to explore changing Option values with for-comprehension. These functions describe patterns which are common to many Scala types other than Option: understanding them’s crucial because you’re going to encounter them in many different contexts. Finally, you are going to learn how to combine optional values in an order sequence using flatMap. You’ll see how to simplify a nested optional structure using flatten. You’re going to learn how to transform an optional value using map. In this article, I’ll introduce you to some of the most common and useful predefined functions on Option. After working with optional types for some time, you’ll realize that some of its operations are particularly recurrent: Option offers you a set of high order functions for them, allowing you to be more productive and not need to use pattern matching every time. You may have discovered the type Option, and how to pattern match with it.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |