Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making code more functionally readable

Tags:

scala

I am looking at following snippet. When map-getOrElse and nested patten matching increases in the code it doesn't look so elegant. What better options do you suggest?

 case MyMessage =>
        val image = (request \ "image").asOpt[String]
        image.map { im =>
          val conf = (request \ "confirmation").asOpt[String]
          conf.map { cf =>
            //code to retrieve ride

            ride match {
              case Some(r) =>
                if (booleanCondition) sender ! SuccessCommand(JsBoolean(true), command)
                else sender ! FailureCommand("Problem updating", command)
              case None => sender ! FailureCommand("Ride empty", command)
            }

          } getOrElse (sender ! FailureCommand("Missing number", command))

        } getOrElse (sender ! FailureCommand("Missing image", command))
like image 437
user2066049 Avatar asked Jan 27 '26 14:01

user2066049


1 Answers

Whenever you are mapping over an Option with a function that produces an Option, you should consider whether you should be using flatMap:

def f(x: Int): Option[Int] = Some(x + 1)

f(1).flatMap(x => f(x)).flatMap(y => f(y))               // Some(4)
f(1).flatMap(x => f(x)).flatMap(y => f(y)).getOrElse(0)  // 4

You can also use for-comprehensions for this, which is really nice for having clean code when you have long chains of these:

(for(x <- f(1); y <- f(x); z <- f(y)) yield z).getOrElse(0)
like image 145
dhg Avatar answered Jan 29 '26 04:01

dhg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!