Skip to content

Instantly share code, notes, and snippets.

@cameronhunter
Created April 19, 2013 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cameronhunter/5422341 to your computer and use it in GitHub Desktop.
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.
/* 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