title: Conditionally invoke member function without a temporary var
body: <p>I have an expression returning an object, and I want to invoke a method on the resulting object only if a certain boolean condition is true. I want to get the result (whether the object, or the result of invoking the method on the object) in a val.</p>
  
  <p>One way is to use a temporary var, such as in the following example, in which <code>List(3, 1, 2)</code> is the (potentially complicated) expression returning an object, <code>list</code> is the temporary var, and <code>.sorted</code> is the method I want to conditionally invoke:</p>
  
  <pre><code>import scala.util.Random
  
  val condition = Random.nextBoolean
  val result = {      
    var list = List(3, 1, 2);
    if (condition) list = list.sorted
    list
  }
  </code></pre>
  
  <p>What would be the canonical way to do this, perhaps <em>without</em> using a temporary var?</p>
  
  <p>Note that</p>
  
  <pre><code>if (condition) List(3, 1, 2).sorted else List(3, 1, 2)
  </code></pre>
  
  <p>is not quite satisfactory because <code>List(3, 1, 2)</code> may in general be a complicated expression that I don't want to repeat.</p>
  
  <p>Here is one method I found that unfortunately involves giving explicit types (and is longer and more complicated than introducing a temporary var as above):</p>
  
  <pre><code>val condition = Random.nextBoolean
  val result =
    (
      if (condition)
        {l: List[Int] =&gt; l.sorted}
      else
        identity(_: List[Int])
    ).apply(List(3, 1, 2))
  </code></pre>
  
  <p>I suspect there must be a tidier way that I have failed to recognize.</p>
  
  <p><em>Update:</em> A slightly less ugly method that unfortunately still requires explicit type information:</p>
  
  <pre><code>val condition = Random.nextBoolean    
  val result = {
      l: List[Int] =&gt; if (condition) l.sorted else l
    }.apply(List(3, 1, 2))
  </code></pre>