Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substitute an empty string (or null) with a default string concisely in Scala

Tags:

string

scala

I have a method that returns a String. I want to substitute it with a default value such as "<empty>" if it returns an empty string or null. Let's assume its name is getSomeString, it is an expensive operation so I can call it only once, and I can't change its return type to Option[String]. For now, I'm doing the following:

val myStr = {
  val s = getSomeString
  if (s == null || s.isEmpty) "<empty>" else s
}

Is there a simpler way to achieve the same thing?

like image 933
trustin Avatar asked Aug 24 '13 10:08

trustin


1 Answers

val myStr = Option(getSomeString).filterNot(_.isEmpty).getOrElse("<empty>")

Updated

I posted this code because I think the intent in this code is clear than if/else or pattern matching version, but I didn't consider the performance issue.

As the others in comments mentioned, this code is much slower than simple if / else or pattern matching(this line will create a lot new objects which is an expensive operation), so please do not use this code when performance is an issue.

like image 78
Brian Hsu Avatar answered Oct 06 '22 01:10

Brian Hsu