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?
val myStr = Option(getSomeString).filterNot(_.isEmpty).getOrElse("<empty>")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With