title: Repeating function call until we'll get non-empty Option result in Scala
body: <p>A very newbie question in Scala - how do I do "repeat function until something is returned meets my criteria" in Scala?</p>
  
  <p>Given that I have a function that I'd like to call until it returns the result, for example, defined like that:</p>
  
  <pre><code>def tryToGetResult: Option[MysteriousResult]
  </code></pre>
  
  <p>I've come up with this solution, but I really feel that it <em>is</em> ugly:</p>
  
  <pre><code>var res: Option[MysteriousResult] = None
  do {
    res = tryToGetResult
  } while (res.isEmpty)
  doSomethingWith(res.get)
  </code></pre>
  
  <p>or, equivalently ugly:</p>
  
  <pre><code>var res: Option[MysteriousResult] = None
  while (res.isEmpty) {
    res = tryToGetResult
  }
  doSomethingWith(res.get)
  </code></pre>
  
  <p>I really feel like there is a solution without <code>var</code> and without so much hassle around manual checking whether <code>Option</code> is empty or not.</p>
  
  <p>For comparison, Java alternative that I see seems to be much cleaner here:</p>
  
  <pre><code>MysteriousResult tryToGetResult(); // returns null if no result yet
  
  MysteriousResult res;
  while ((res = tryToGetResult()) == null);
  doSomethingWith(res);
  </code></pre>
  
  <p>To add insult to injury, if we don't need to <code>doSomethingWith(res)</code> and we just need to return it from this function, Scala vs Java looks like that:</p>
  
  <h3>Scala</h3>
  
  <pre><code>def getResult: MysteriousResult = {
    var res: Option[MysteriousResult] = None
    do {
      res = tryToGetResult
    } while (res.isEmpty)
    res.get
  }
  </code></pre>
  
  <h3>Java</h3>
  
  <pre><code>MysteriousResult getResult() {
      while (true) {
          MysteriousResult res = tryToGetResult();
          if (res != null)  return res;
      }
  }
  </code></pre>