J_Kowiak
J_Kowiak

Reputation: 1

How do I make scala program loop and read every letter in string

I'm trying to make the program go through a predetermined string and read each character 1 by 1 in a manner similar to what I have posted. The IDE tells me that I cannot do "cs >= 1" because ">=" is not part of "(Char => Boolean) => Int".

def move(s: String) {
  var chemov = s.take(1)
  var cs = s.count(_)
  while (cs >= 1){
    ad()
    s.drop(1)
  }
}

Upvotes: 0

Views: 96

Answers (1)

tillaert
tillaert

Reputation: 1845

s.count() does not give you the length of the s, but it gives you the number of occurences that the predicate matches. By just supplying an underscore, cs is not an integer, but a function. That is why you get your error. You can get the size with s.length

If you want to use count, then you have to supply a function:

var cs = s.count(_ => true)

Alternatively, you can just iterate over the string:

s.foreach( c => {
    ad()
})

Upvotes: 2

Related Questions