Using the Scala Option, Some, and None idiom (instead of Java null)
A powerful Scala idiom is to use the Option
class when returning a value from a function that can be null. Simply stated, instead of returning one object when a function succeeds and null when it fails, your function should instead return an instance of an Option, where the instance is either:
- In the success case, return an instance of the Scala Some class
- In the failure case, return an instance of the Scala None class
Because Some
and None
are both children of Option
, your function signature just declares that you're returning an Option that contains some type (such as the Int
type shown below). At the very least, this has the tremendous benefit of letting the user of your function know what’s going on.