A Scala 3 function that counts the number of vowels in the String it is given as input

As a brief note today, here’s a Scala 3 function that counts the number of vowels in the String it is given as input:

def countVowels(s: String): Int =
    val vowels = Set('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
    s.count(vowels.contains)

Note that this works because as I have mentioned in other places, a Scala Set can be used as a function — specifically as a predicate — and the count function on the Scala sequence classes expects a predicate.

Scala 2 solution

Also note that if you want to use this function with Scala 2, just add curly braces around the body of the function:

def countVowels(s: String): Int = {
    val vowels = Set('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
    s.count(vowels.contains)
}