Computer scienceProgramming languagesKotlinObject-oriented programmingClass hierarchy

Functional (SAM) interfaces

Counting the total number of vowels

Report a typo

This Kotlin code includes a functional interface named StringProcessor and a main function for processing a string sequence to count vowels. Here's a detailed explanation of its parts:

  1. Functional Interface StringProcessor:

    • This is an interface with a single abstract method called process. It accepts a String as input and gives back an Int.

    • As a functional interface (marked by fun interface), a lambda expression can be used to implement it.

  2. Main Function:

    • In the main function, a StringProcessor instance is created named countVowels.

    • This instance uses a lambda expression to count vowels in a string. The lambada expression str.count { it in "aeiouAEIOU" } identifies characters in str that are vowels, either in lowercase or uppercase.

    • Then, a string sequence is created with generateSequence { readLine() }. This sequence goes on reading standard input lines until it encounters an empty string.

    • With takeWhile { it.isNotEmpty() }, the sequence only proceeds if non-empty strings are entered.

    • Lastly, sumOf { countVowels.process(it) } calculates the total vowel count from all input strings by applying the countVowels processor to every string in the sequence and adding up the results.

    • The total vowel count is displayed using println(totalVowels).

Reorder lines using drag or arrows. Adjust indentation with left buttons
                val countVowels = StringProcessor { str ->
              
                }
              
                str.count { it in "aeiouAEIOU" }
              
                fun process(input: String): Int
              
                }
              
                val totalVowels = strings.sumOf { countVowels.process(it) }
              
                fun interface StringProcessor {
              
                fun main() {
              
                println(totalVowels)
              
                val strings = generateSequence { readlnOrNull() }.takeWhile { it.isNotEmpty() }
              
                }
              

Create a free account to access the full topic