coder25
coder25

Reputation: 2393

Possible ways to reuse repeated logic and getOrElse chaining in Scala

I have a logic like

if(condition) statement1 else if(condition) statement2 else .......

Code:

val a: Option[String] = if (source == "abc") Some(source) else None
val b: Option[String] = if (source == "cdf") Some(source) else None
......nor 3 4 statments as above

val test: String = a.getOrElse(b.getOrElse(StringUtils.EMPTY))

Question:

  1. Can anyone suggest a better way to reuse the code with if logic in a functional way?
  2. Any alternative to getOrElse chaining?

Update

By "reuse" I mean in case I have seven or eight if conditions. Any way to generalise the condition inside if and then reuse it? I want to create a filter. I am new to Scala and am not sure if we can use high order functions or any other approach.

Upvotes: 0

Views: 267

Answers (3)

mkUltra
mkUltra

Reputation: 3068

Very similar with orElse, for me it is clearer way to manipulate Options:

a.orElse(b).getOrElse(StringUtils.EMPTY)

Upvotes: 0

Dima
Dima

Reputation: 40510

It's not clear from your example, what it is exactly you are trying to do. The functional way to write if is .filter, and you can use .orElse instead of .getOrElse ... But I don't quite understand the purpose of having those multiple assignments, and convertions of strings to options and back the way you wrote it. Most probably, they are unnecessary, and there is a better way to do what you want, but it's hard to suggest one without understanding of what it is that you actually need.

val a = Option(source).filter(_ == "abc")
val b = Option(source).filter(_ == "cdf") 

val test = a orElse b getOrElse("")

Alternatively, you could just write:

val test = Option(source).filter(Set("abc", "cdf")).getOrElse("")

Or even:

val test = source match {
  case "abc"|"cdf" => source
  case _ => ""
}

Upvotes: 1

Sergey Kovalev
Sergey Kovalev

Reputation: 9411

val test = source match
{
  case "abc" => /* your code here */
  case "cdf" => /* your code here */
  ...
  case _ => None
}

Upvotes: 0

Related Questions