Scala Parentheses Balancing in Functional Programming

I was working on the problem to check if the parenthesis are balanced using Scala.


  • balance("(Hello (my) name is (StackOverflow))") -> True
  • balance("(Hello (my) name is StackOverflow))(((((((") -> False

The following implementation is working, however I’m wondering: What would you suggest to change in this implementation to make it more functional?

In particular I don’t like the use of try-catch in this solution.

  import scala.collection.mutable.Stack

  val OPEN_PARENTHESIS: Char = '('
  val CLOSED_PARENTHESIS: Char = ')'

  def balance(chars: List(Char)): Boolean =
    val parentheses = chars.filter(char => char == OPEN_PARENTHESIS || char == CLOSED_PARENTHESIS)
    val emptyStack = Stack(Char)()
    isBalanced(parentheses, emptyStack)

  private def isBalanced(chars: List(Char), stack: Stack(Char)): Boolean = chars match
    case Nil => stack.isEmpty
    case x :: xs =>
      try {
        val nextStack = processChar(x, stack)
        isBalanced(xs, nextStack)
      } catch {
        case e: Exception => false

  private def processChar(char: Char, stack: Stack(Char)): Stack(Char) = char match
    case char if char == OPEN_PARENTHESIS => stack.push(char)
    case char if char == CLOSED_PARENTHESIS => stack.tail
    case _ => throw new IllegalArgumentException("The given char is not valid")