title: " Exception in thread "main" java.util.NoSuchElementException: head of empty list " error and more in Scala
body: <p>I wrote a recursive parentheses balancing function and there doesnt seem to be any errors in the code but when I run it I get a lot of errors.</p>
  
  <p>I wrote the function with a call like this:</p>
  
  <pre><code>if(balance("blarg(arg)".toList)) println("true!") else println("false")
  </code></pre>
  
  <p>and a definition like this:</p>
  
  <pre><code>def balance(chars: List[Char]): Boolean ={
  
        implicit class MutableInt(var value: Int) 
        {
            def inc() = { value+=1 } 
            def dec() = { value-=1 }                  
        }
  
          var stack: Int = 0
  
          def recursbalance(chars: List[Char], stack: Int): Boolean=
          {
  
              if ((chars.head: Char) == "(".toList) stack.inc()
              else if ((chars.head: Char) == ")".toList) stack.dec()
  
              if (stack&lt;0) false
  
              if (chars.isEmpty: Boolean) if (stack == 0) true else false  
  
              recursbalance(chars.tail: List[Char], stack: Int)
  
          }
      recursbalance(chars: List[Char], stack: Int)
  }
  </code></pre>
  
  <p>I'm getting these errors:</p>
  
  <pre><code>Exception in thread "main" java.util.NoSuchElementException: head of empty list
  at scala.collection.immutable.Nil$.head(List.scala:337)
  at scala.collection.immutable.Nil$.head(List.scala:334)
  at recfun.Main$.recursbalance$1(Main.scala:45)
  at recfun.Main$.balance(Main.scala:55)
  at recfun.Main$.main(Main.scala:16)
  at recfun.Main.main(Main.scala)
  </code></pre>
  
  <p>How do I fix?
  sorry for any noobness, I'm new to Scala.</p>
  
  <p>I tried replacing my recursive calls with this:</p>
  
  <pre><code>   if (chars.isEmpty: Boolean) {
         if (stack == 0) true else false  
     }
     else
         recursbalance(chars.tail: List[Char], stack: Int) 
  </code></pre>
  
  <p>but i still got all the errors..</p>