0
0
Kotlinprogramming~15 mins

Extension function syntax in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Extension Function Syntax in Kotlin
📖 Scenario: Imagine you want to add a new feature to the String type in Kotlin without changing its original code. You will create an extension function that adds a fun greeting to any string.
🎯 Goal: Build a Kotlin program that defines an extension function called greet for the String type. This function will return a greeting message using the string it is called on.
📋 What You'll Learn
Create a variable called name with the value "Alice".
Create an extension function called greet for the String type that returns a greeting message.
Call the greet function on the name variable and store the result in a variable called message.
Print the message variable.
💡 Why This Matters
🌍 Real World
Extension functions let developers add new features to existing classes like <code>String</code> or <code>Int</code> without modifying their source code. This is useful when working with libraries or built-in types.
💼 Career
Knowing extension functions is important for Kotlin developers because it helps write cleaner, more readable, and reusable code. It is a common technique in Android app development and Kotlin backend projects.
Progress0 / 4 steps
1
Create a String variable
Create a variable called name and set it to the string "Alice".
Kotlin
Need a hint?

Use val name = "Alice" to create the variable.

2
Define an extension function
Define an extension function called greet for the String type. It should return a string in the format "Hello, <string>!" where <string> is the string the function is called on.
Kotlin
Need a hint?

Use fun String.greet(): String to start the extension function and return "Hello, $this!" to create the greeting.

3
Call the extension function
Call the greet function on the variable name and store the result in a variable called message.
Kotlin
Need a hint?

Use val message = name.greet() to call the extension function.

4
Print the greeting message
Print the variable message to display the greeting.
Kotlin
Need a hint?

Use println(message) to print the greeting.