I have a piece of code implemented in 2 ways:
val c = if(x.y.isDefined){
methodA(....)
} else {
method(....)
}
c
And this:
val c = x.y.
map(methodA(....))
.orElse(Some(mehodB(....))
.getOrElse("")
c
x.y is an Option and methodA, methodB return String values.
Which of these approaches is more preferred in Scala? Personally I find first one to be more easy to understand, but my more scala proficient colleague prefers second one.
CodePudding user response:
use the if
or something based on pattern match (by the way, no need for assigning to c if you return the expression)
x.y match {
case Some(_) => methodA()
case None => methodB()
}
CodePudding user response:
x.fold(methodB) { _ => methodA }