0

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?

1
  • 1
    Although in Scala null is discouraged, if you're using an API that returns null you have to deal with null. Since your code immediately deals with it, I think it's fine and as "scala way" as anything else. Sure, you can wrap it in an option as thee other answers to, but why, if all you'll do is immediately unwrap it. Commented Aug 26, 2015 at 17:35

2 Answers 2

2

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("")
Sign up to request clarification or add additional context in comments.

3 Comments

You have to deal with "null" if ex.getMessage can return it. In this case, hiding it just obscures what/s going on. I think the original is fine.
@Paul Although, I agree with you that the original is fine, I have to say, if this is supposed to be a formatter for the sole purpose dealing with null return value of ex.getMessage, than hiding that null does not seem to do much harm.
It's that Option.apply + map + getOrElse is a lot of machinery to just (in effect) test for null. It take a lot more thought to see what the code is doing. In that sense, I think it is harmful
2

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

2 Comments

I think this is considerably less clear than the original. Which is fine to me
"Our servers encountered an error" + { val m = ex.getMessage; if (x == null || x.isEmpty) "" else m} :) Although the match/case is fine too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.