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 somePlay framework magic? Calling a null variable worked without exception.
The reason
Optionis less verbose is that you don’t need to do those null checks. In other words, yourmatch/caseverbosity is unnecessary.Let’s assume we have these two variables:
If we want to call a function things that are
Somerather thanNone, we don’t need to null-check: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.
There are plenty more examples of how
Optioncleans things up, but this should give you an idea.