title: Chain multiple functions in Scala while a condition holds
body: <p>Suppose we have 3 methods which all return an <code>Option</code></p>
  
  <pre class="lang-scala prettyprint-override"><code>import scala.util.Try
  
  def divideSafe(d: Int): Option[Int] = Try(42 / d).toOption
  def sqrtSafe(x: Double): Option[Double] = if(!math.sqrt(x).isNaN) Some(math.sqrt(x)) else None
  def convertSafe(s: String): Option[Int] = Try(s.toInt).toOption
  </code></pre>
  
  <p>Now I want to chain them while a condition holds. In my case, if the result from the previous method is defined then should go to the next one. And as long as the condition is false, then stop the operation and return a default value.</p>
  
  <p>I can obtain the desired result with nested if-else statements:</p>
  
  <pre class="lang-scala prettyprint-override"><code>def superSafe(d: Int, x: Double, s: String): Unit = {
    if (divideSafe(d).isDefined) {
      println(divideSafe(d).get.toString)
      if (sqrtSafe(x).isDefined) {
        println(sqrtSafe(x).toString)
        if (convertSafe(s).isDefined) {
          println(convertSafe(s).get.toString)
        } else {
          println("Converting failed")
        }
      } else {
        println("Sqrt failed")
      }
    } else {
      println("Dividing failed")
    }
  }
  </code></pre>
  
  <p>Therefore:</p>
  
  <p><code>superSafe(1, -1, "5")</code> would print 42 and Sqrt failed
  <code>superSafe(0, 4, "cat")</code> would print Dividing failed
  <code>superSafe(42, 4, 1)</code> would print 1,2,1</p>
  
  <p>However I want to avoid the nested if-else statements and I am interested if there is a functional way in Scala to solve this kind of problems.</p>
  
  <p>I want something like <code>orElse</code> statement, but the other way around.</p>
  
  <p>The desired function could be used like this:</p>
  
  <pre class="lang-scala prettyprint-override"><code>divideSafe(42) ifThen("Dividing failed") sqrtSafe(-4) ifThen("Sqrt failed") convertSafe("cat") ifThen("Converting failed")
  </code></pre>