Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return second string if first is empty?

Tags:

scala

Here is an idiom I find myself writing.

def chooseName(nameFinder: NameFinder) = {
  if(nameFinder.getReliableName.isEmpty) nameFinder.getReliableName
  else nameFinder.secondBestChoice
}

In order to avoid calling getReliableName() twice on nameFinder, I add code that makes my method look less elegant.

def chooseName(nameFinder: NameFinder) = {
  val reliableName = nameFinder.getReliableName()
  val secondBestChoice = nameFinder.getSecondBestChoice()
  if(reliableName.isEmpty) reliableName
  else secondBestChoice
}

This feels dirty because I am creating an unnecessary amount of state using the vals for no reason other than to prevent a duplicate method call. Scala has taught me that whenever I feel dirty there is almost always a better way.

Is there a more elegant way to write this?

Here's two Strings, return whichever isn't empty while favoring the first
like image 517
Cory Klein Avatar asked Mar 16 '26 12:03

Cory Klein


1 Answers

There's no need to always call getSecondBestChoice, of course. Personally, I find nothing inelegant about the code after changing that - it's clear what it does, has no mutable state. The other answers just seem overcomplicated just to avoid using a val

def chooseName(nameFinder: NameFinder) = {
  val reliableName = nameFinder.getReliableName()

  if(reliableName.isEmpty) reliableName
  else nameFinder.getSecondBestChoice()
}

If you really want to avoid the val, here's another variant (generalises well if there are more than two alternatives)

List(nameFinder.getReliableName(), nameFinder.getSecondBestChoice()).find(_.nonEmpty).get

(or getOrElse(lastResort) if everything in the list may be empty too)

like image 188
The Archetypal Paul Avatar answered Mar 18 '26 00:03

The Archetypal Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!