Expecting null in Scala. Should Option be used?

playframework, scala

Solution

The reason `Option` is less verbose is that you don't need to do those null checks. In other words, your `match/case` verbosity is unnecessary.

Let's assume we have these two variables:

val x: Option[Int] = Some(5)
val y: Option[Int] = None

If we want to call a function things that are `Some` rather than `None`, we don't need to null-check:

x foreach println  // prints 5
y foreach println  // nothing printed

Or if we want to apply a function and get a new result, it's similar, and keeps track of whether the input was present or not.

val f = (i: Int) => i + 1
x map f  // Some(6)
y map f  // None

There are plenty more examples of how `Option` cleans things up, but this should give you an idea.

Problem

I have a play template in which the most typical scenario for a parameter is "null". I have understood that idiomatic Scala favors Option instead. My first intuition coming from java would be using null. Case with null: In Controller ``` views.html.addPost(errors.errorsAsJson) ``` In View ``` @(errors: play.api.libs.json.JsValue = null) ... @if(errors != null){@errors} ``` Case with Option: In Controller ``` views.html.addPost(Option(errors.errorsAsJson)) ``` In View ``` @(errors: Option[play.api.libs.json.JsValue] = None) ... @{errors match { case None => {} case _ => {errors.get} } } ``` Update: I got it now. Instead of: ``` @{errors match { case None => {} case _ => {errors.get} } } ``` I could just do ``` @errors ``` Update 2: Apparently I didn't have to do the null check with null either? Maybe some`Play framework` magic? Calling a null variable worked without exception.

Original source