title: Scala: if statement returning Any instead of Unit in a closure
body: <p>I have the following code in a method:</p>
  
  <pre><code>aSides.foreach(as =&gt; as.side.terr match
  {
    case r: TerrSRiver =&gt; paintSeq :+= ((g: Graphics2D) =&gt;
      {
        g.setPaintColour(ColourInt.blue)
    g.fill(Polygon(as.paintStd(0.2)))
      }
    case _: TerrSCoast =&gt; paintSeq :+= ((g: Graphics2D) =&gt;
      {
        g.setPaintColour(TerrSea.colour)
        g.fill(Polygon(as.paintStd(0.2)))
      }) //one case excluded for simplicity
  </code></pre>
  
  <p>paintSeq is declared outside the method</p>
  
  <pre><code>var paintSeq: Seq[Graphics2D =&gt; Unit] = Nil
  </code></pre>
  
  <p>This compiles and runs as expected. However if I add an if Statement to the first case:</p>
  
  <pre><code>case r: TerrSRiver =&gt; paintSeq :+= ((g: Graphics2D) =&gt;
    {
      g.setPaintColour(ColourInt.blue)
      g.fill(Polygon(as.paintStd(0.2)))
      if (zoom &gt; 50) g.setPaintColour(ColourInt.white)
    }
  </code></pre>
  
  <p>I get an error:</p>
  
  <p>type mismatch;  found : Seq[swing.Graphics2D => Any]  required: Seq[swing.Graphics2D => Unit]  AreaESw.scala   /prStratSw/src/pGrid/pUISw  line 49 Scala Problem</p>
  
  <p>The error refers to the paintSeq :+= method. <strong>Why is the if statement returning Any rather than Unit?</strong> I can get rid of the error by adding a line after the if statement:</p>
  
  <pre><code>val dummy = 0
  </code></pre>
  
  <p>However if I add in return Unit at the end:</p>
  
  <pre><code>case r: TerrSRiver =&gt; paintSeq :+= ((g: Graphics2D) =&gt;
    {
      g.setPaintColour(ColourInt.blue)
      g.fill(Polygon(as.paintStd(0.2)))
      if (zoom &gt; 50) g.setPaintColour(ColourInt.white)
      return Unit
    }
  </code></pre>
  
  <p>It Compiles with the following warning:</p>
  
  <p>enclosing method setVisObjs has result type Unit: return value discarded</p>
  
  <p>But when it runs I get the following error  </p>
  
  <p>Exception in thread "AWT-EventQueue-0" scala.runtime.NonLocalReturnControl$mcV$sp</p>
  
  <p>Using "return ()" still gives the run time exception.</p>
  
  <p>This is Scala Swing code, but I'm using Scala 2.10.3 in the JavaFx Eclipse download: 4.2.2 on Linux.</p>