Last updated: January 6, help support my writing at ko-fi.
This example is a little contrived, but if you have a situation where one Option instance contains one or more other Options, this article may be helpful. But once I a swore off using null values, and b learned how to properly work with Options, I saw the beauty of the approach. For instance, one look at this class definition tells you that there may or may not be a street2 field; as the Option wrapper type nested option, its optional.
C Programming Tutorial - 18 - Nesting if Statements
When Options contain other Options nested Options Now imagine a case where you have an Option[Person] in an application. How would you do this?
Now all you have to do is to fill out the body of the function to match that signature. Depending on your needs, you can use a similar approach with any monad, i.
Note: There is a cleaner version of this approach in the Comments section below. Some sample data A couple of examples will show how getStreet2 works. Motivations My main reason for writing this article was to demonstrate two ways to deal with Option instances that contain other Options.
As shown, you can use a flatMap or b a for expression to traverse the Nested option to get the value you want. A second reason for writing this article was to give you a little more exposure to flatMap.
When I first learned Scala, I always thought of flatMap in terms of collections classes, but once you get into other monadic data types like Option, Try, Either, etc.
- What they write about the site how to make money
- : The HTML Select element - HTML: HyperText Markup Language | MDN