I have this scala code that involves java:
val message = "Our servers encountered an error" +
(if (ex.getMessage == null) "" else (": " + ex.getMessage))
What is the scala best way to write it?
I have this scala code that involves java:
val message = "Our servers encountered an error" +
(if (ex.getMessage == null) "" else (": " + ex.getMessage))
What is the scala best way to write it?
In scala you do not want to deal with null, it is more convenient to use Option
"Our servers encountered an error while processing your request " +
Option(ex.getMessage).map(":"+_).getOrElse("")
null return value of ex.getMessage, than hiding that null does not seem to do much harm.Probably something along the lines of:
val exMessage = Option(ex.getMessage).fold("")(m =>s": $m")
val message = s"Our servers encountered an error$exMessage"
or in one line:
s"Our servers encountered an error${ Option(ex.getMessage).fold("")(m =>s": $m") }"
Though, not the most efficient way. Nor will it make your code any clearer.
EDIT:
This will (as well as the original) probably yield an undesired result if ex,getMessage returns an empty String.
Additionally, as has been mentioned, using Option in such a situation is a good way to obfuscate your code. So here is an example that should be more readable:
def errorMessage(ex: Throwable): String= {
val formattedMsg = ex.getMessage match {
case msg: String if msg.nonEmpty => s": $msg"
case _ => ""
}
s"Our servers encountered an error$formattedMsg"
}
"Our servers encountered an error" + { val m = ex.getMessage; if (x == null || x.isEmpty) "" else m} :) Although the match/case is fine too.