Skip to content

Instantly share code, notes, and snippets.

@gclaramunt
Created February 21, 2015 18:06
Show Gist options
  • Save gclaramunt/c37e75c08b1cd7d50716 to your computer and use it in GitHub Desktop.
Save gclaramunt/c37e75c08b1cd7d50716 to your computer and use it in GitHub Desktop.
Option vs null
def fun(k:Int)={
val x = f(k)
val y = g(x)
val z = h(y)
x+y+z
}
// If f,g,h return Option
def fun1(k:Int)=for {
x <- f(k)
y <- g(x)
z <- h(y)
} yield {x+y+z}
// If f,g,h return null
def fun2(k:Int)=for {
x <- Option(f(k)))
y <- Option(g(x))
z <- Option(h(y))
} yield {x+y+z}
// With Option you can keep the program structure, with null you can't :
def fun4(k:Int)= {
val x=f(k)
if (x != null) {
val y= g(x)
if (y != null) {
val z=h(z)
if (z != null) x+y+z else null
} else null
} else null
}
//Also, Option is a different type than the normal value, and the compiler will signal if you mix both, unlike null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment