0
0
Kotlinprogramming~15 mins

Extensions on built-in types in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Extensions on built-in types in Kotlin
📖 Scenario: You are working on a Kotlin project where you want to add new useful functions to existing types without changing their original code. This is common when you want to make your code cleaner and easier to read.
🎯 Goal: You will create an extension function on the String type to count vowels, then use it in a program to show how many vowels a word has.
📋 What You'll Learn
Create an extension function on the String type called countVowels
The countVowels function returns the number of vowels in the string
Use the extension function on a sample string
Print the result
💡 Why This Matters
🌍 Real World
Extension functions let you add new abilities to existing types like strings or numbers. This makes your code cleaner and easier to read, like adding new tools to your toolbox without changing the tools themselves.
💼 Career
Many Kotlin projects use extension functions to improve code quality and maintainability. Knowing how to write and use them is important for Kotlin developers in app development and backend services.
Progress0 / 4 steps
1
Create a sample string
Create a variable called word and set it to the string "Kotlin".
Kotlin
Need a hint?

Use val word = "Kotlin" to create the string variable.

2
Create an extension function to count vowels
Create an extension function on String called countVowels that returns an Int. It should count the vowels a, e, i, o, u in the string ignoring case.
Kotlin
Need a hint?

Use fun String.countVowels(): Int and inside use this.count { it.lowercaseChar() in "aeiou" }.

3
Use the extension function on the string
Create a variable called vowelCount and set it to the result of calling countVowels() on the variable word.
Kotlin
Need a hint?

Use val vowelCount = word.countVowels() to call the extension function.

4
Print the vowel count
Print the text "Number of vowels in Kotlin: " followed by the value of vowelCount using println.
Kotlin
Need a hint?

Use println("Number of vowels in Kotlin: $vowelCount") to show the result.