I am just beginning Scala, so bear with me.
I am writing a method that returns boolean based on the number of “*” found in a given list.
def stars(n: Int, chars: List[Char]): Boolean = {
var count = 0
chars.foreach{ letter =>
if (letter == "*") {
count += 1
}
if (count == n) {
return true
}
}
false
} //> stars: (n: Int, chars: List[Char])Boolean
stars(5, "******".toList) //> res12: Boolean = false
That should’ve returned true. Because it should’ve ended prematurely when the count becomes 5, which becomes equal to n.
What am I doing wrong?
Doesn’t scala allow ending a method prematurely with return statement?
In
if (letter == "*")you are comparing char with string and thus constantly getting false and yourcount += 1is never evaluatedYou have to write
if (letter == '*')insteadActually, much more idiomatic code would be: