oshai
oshai

Reputation: 15365

what is the "scala" way to write this code

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?

Upvotes: 0

Views: 322

Answers (2)

Sascha Kolberg
Sascha Kolberg

Reputation: 7162

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"
}

Upvotes: 2

grotrianster
grotrianster

Reputation: 2468

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("")

Upvotes: 2

Related Questions