The error is stating that getParentheses
expects a String
as return value but your function returns Unit
. The last line in a Scala function is the return value which in your case is an if
which returns Unit
. You would have to refactor the second if
. Here's how I would do it with pattern matching.
def getParentheses(chars: List[Char]): String = chars match {
case h::t if h == '(' || h == ')' => h + getParentheses(t)
case h::t => getParentheses(t)
case Nil => ""
}
It's probably more idiomatic to do it with filter
though.
scala> List(')', 'a', ')').filter(x => x == ')' || x == '(')
res0: List[Char] = List(), ))