title: Coalescing options in Scala
body: <p>Most SQL implementations (this question has nothing to do with SQL, it is just an example) offer the function <code>COALESCE(x1,x2,...,xn)</code> which returns <code>x1</code> if it is not <code>NULL</code>, <code>x2</code> otherwise only if <code>x2</code> is not <code>NULL</code> neither and so on. If all <code>xi</code> values are <code>NULL</code> then the result is <code>NULL</code>.</p>
  
  <p>I wanted to get something like SQL's <code>COALESCE</code> in Scala for <code>Option</code> values being <code>NULL</code> replaced by <code>None</code>. I'll give you some examples:</p>
  
  <pre><code>&gt; coalesce(None,Some(3),Some(4))
  res0: Some(3)
  
  &gt; coalesce(Some(1),None,Some(3),Some(4))
  res1: Some(1)
  
  &gt; coalesce(None,None)
  res2: None
  </code></pre>
  
  <p>So I implemented it as:</p>
  
  <pre><code>def coalesce[T](values: Option[T]*): Option[T] = 
      (List[T]() /: values)((prev: List[T], cur: Option[T]) =&gt;
                            prev:::cur.toList).headOption
  </code></pre>
  
  <p>It works fine but I wonder if already exists something like this function implemented as part of Scala.</p>