Created
April 19, 2013 18:44
-
-
Save cameronhunter/5422341 to your computer and use it in GitHub Desktop.
Option doesn't solve everything. Sometimes overloaded functions provide a less confusing API.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Function using Option */ | |
object Hello { | |
def to(name: Option[String] = None) = | |
"Hello " + (name getOrElse "world") | |
} | |
println(Hello.to(null)) // Causes NullPointerException | |
println(Hello.to(Some(null))) // "Hello null" | |
/* Overloading functions but using an underlying Option prevents the possibility of NullPointerException */ | |
object Hello { | |
def to = | |
to(name = None) | |
def to(name: String) = | |
to(name = Option(name)) | |
private def to(name: Option[String]) = | |
"Hello " + (name getOrElse "world") | |
} | |
println(Hello.to(null)) // "Hello world" | |
println(Hello.to(Some(null))) // Not possible |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment