I am trying to learn Scala and am a newbie. I know that this is not optimal functional code and welcome any advice that anyone can give me, but I want to understand why I keep getting true for this function.
def balance(chars: List[Char]): Boolean = {
val newList = chars.filter(x => x.equals('(') || x.equals(')'));
return countParams(newList, 0)
}
def countParams(xs: List[Char], y: Int): Boolean = {
println(y + " right Here")
if (y < 0) {
println(y + " Here")
return false
} else {
println(y + " Greater than 0")
if (xs.size > 0) {
println(xs.size + " this is the size")
xs match {
case xs if (xs.head.equals('(')) => countParams(xs.tail, y + 1)
case xs if (xs.head.equals(')')) => countParams(xs.tail, y - 1)
case xs => 0
}
}
}
return true;
}
balance("()())))".toList)
I know that I am hitting the false branch of my if statement, but it still returns true at the end of my function. Please help me understand. Thanks.
You either must be more explicit in what you are returning or make it more explicit for the compiler. This works:
In the code above each branch of
ifreturns some value so the compiler assumes it’s a value to be returned. BTW version without logging and much more idiomatic: