The trivial approach (with if
,else
), is known. I'm thinking about how Scala can help me to do it in a more elegant way:
def prepareData(baseObj: BaseObj): Option[NextObj] = {
val maybeDataOne = Option(baseObj.getDataOne)
val maybeDataTwo = Option(baseObj.getDataTwo)
// return None if no DataOne or DataTwo defined
// return Some(NextObj) if at least one of the Datas defined.
// trivial solution:
if(maybeDataOne.isDefined || maybeDataTwo.isDefined) {
Some(NextObj(
dataOne = baseObj.dataOne,
dataTwo = baseObj.dataTwo
))
} else None
}
//DataOne and DataTwo will be mapped to NextObj, if, at least one, is defined
case class NextObj(d1: Option[DataOne], d2: Option[DataTwo])
maybeDataOne orElse maybeDataTwo map { _ => nextObj }
One way to make this look even prettier is to equip your NextObject
class with a .toOption
method:
def toOption = d1 orElse d2 map { _ => this }
Then you can just write NextObject(maybeDataOe, maybeDataTwo).toOption
at the call site.
Or maybe this:
object NextObject {
def opt(d1: Option[DataOne], d2: Option[DataTwo]) =
d1 orElse d2 map { _ => apply(d1, d2) }
}
and then just NextObject.opt(maybeDataOne, maybeDataTwo)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments