Jason Kim
Jason Kim

Reputation: 19061

scala: return value for a method and end the method prematurely

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?

Upvotes: 3

Views: 2893

Answers (1)

om-nom-nom
om-nom-nom

Reputation: 62855

In if (letter == "*") you are comparing char with string and thus constantly getting false and your count += 1 is never evaluated
You have to write if (letter == '*') instead

Actually, much more idiomatic code would be:

def stars(n: Int, chars: List[Char]): Boolean = {
  n == chars.count(c => c == '*')
}

Upvotes: 4

Related Questions