1

I have 2 option variables and want to assign 2nd one to 1st one when 1st is None or empty string. Is there a better way writing this? I need to do these for 10 other similar properties in a class.

var myoption1: Option[String]
var myoption2: Option[String]

import org.apache.commons.lang3.StringUtils
  implicit class Addons(val s: String) {
    def isEmptyS = StringUtils.isEmpty(s)
    def isNotEmpty = StringUtils.isNotEmpty(s)
  }

if (myoption1.map(_.isEmpty).getOrElse(true) &&
    myoption2.map(_.isNotEmpty).getOrElse(false)
    ) myoption1 = myoption2

1 Answer 1

3

If you don't care which empty string out of 2 will end up in myoption1 if both of them are empty, then I suggest this:

myoption1 = myoption1.filter(_.nonEmpty).orElse(myoption2)
Sign up to request clarification or add additional context in comments.

4 Comments

I know, just thought that StringUtils.isEmpty could contain different logic regarding trimming or whatever. Edited.
shouldn't it be filterNot?
@VictorMoroz The question is to assign 2nd one to 1st one when 1st is None or empty string.
@angelokh it was myoption1.filter(_.isEmpty) at the time I asked

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.