20.6. Using the Option/Some/None Pattern
Problem
For a variety of reasons, including removing
null values from your code, you want to use what I
call the
Option/Some/None
pattern. Or, if you’re interested in a problem (exception) that occurred
while processing code, you may want to return
Try/Success/Failure
from a method instead of
Option/Some/None.
Solution
There is some overlap between this recipe and the previous recipe,
“Eliminate null Values from Your Code”. That recipe shows how to use
Option instead of null in the following situations:
Using
Optionin method and constructor parametersUsing
Optionto initialize class fields (instead of usingnull)Converting
nullresults from other code (such as Java code) into anOption
See that recipe for examples of how to use an Option in those situations.
This recipe adds these additional solutions:
Returning an
Optionfrom a methodGetting the value from an
OptionUsing
Optionwith collectionsUsing
Optionwith frameworksUsing
Try/Success/Failurewhen you need the error message (Scala 2.10 and newer)Using
Either/Left/Rightwhen you need the error message (pre-Scala 2.10)
Returning an Option from a method
The toInt method used in this
book shows how to return an Option
from a method. It takes a String as
input and returns a Some[Int] if
the String is successfully
converted to an Int, otherwise it
returns a None:
deftoInt(s:String):Option[Int]={try{Some(Integer.parseInt(s.trim))}catch{casee:Exception=>None}}
Although this is a simple ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access