Snark Snark - 3 months ago 8
Scala Question

best way to handle multiple options scala

I currently am working with some scala code that has multiple Option types, that I need to set on an object (if they exist

currently I am doing the following

def myFunc(arg1: Option[Int], arg2: Option[Float]) {
val objSet1 = arg1.fold(obj)(obj.setArg1)
val objSet2 = arg2.fold(objSet1)(objSet1.setArg2)
obj.runComputation()
}


I feel like there's a way to do this more elegantly with a for comprehension, but my monad thinking is failing me on how...

Answer

I don't think there's actually anything built in, but you can do this:

implicit class MaybeModifyOps [T](underlying: T) {
  def maybeModify[X](a: Option[X])(f: (T,X) => T): T = a.fold(underlying)(f(underlying,_))
}

and use it like this:

obj
  .maybeModify(arg1)(_ setArg1 _)
  .maybeModify(arg2)(_ setArg2 _)
  .runComputation()