Kotlin — Extensions
Extension functions
fun String.isPalindrome(): Boolean {
return this == this.reversed()
}
fun Int.isEven(): Boolean {
return this % 2 == 0
}
fun main() {
println("racecar".isPalindrome()) // true
println(42.isEven()) // true
}
Extension properties
val String.wordCount: Int
get() = this.split("\\s+".toRegex()).size
fun main() {
val text = "Hello World from Kotlin"
println(text.wordCount) // 4
}
Nullable extensions
fun String?.orDefault(default: String = "N/A"): String {
return this ?: default
}
fun main() {
val name: String? = null
println(name.orDefault()) // N/A
println("Alice".orDefault()) // Alice
}
Extension in classes
class Calculator {
fun Int.square() = this * this
fun Int.cube() = this * this * this
}
fun main() {
val calc = Calculator()
with(calc) {
println(5.square()) // 25
println(3.cube()) // 27
}
}
Scope functions
data class Person(var name: String, var age: Int)
fun main() {
val p = Person("Alice", 30)
// let
p.let {
println("${it.name} is ${it.age}")
}
// apply
p.apply {
name = "Bob"
age = 25
}
println(p) // Person(name=Bob, age=25)
// run
val result = p.run {
"Name: $name, Age: $age"
}
println(result)
// also
val nums = mutableListOf(1, 2, 3)
nums.also { println("List: $it") }.add(4)
// with
with(p) {
println("$name is $age years old")
}
}
Best practices
- Use extensions for utility functions
- Keep extensions focused and small
- Define extensions where they're used
- Use scope functions for object configuration
Mini Practice
Write Kotlin code that:
- Creates an extension function for String
- Uses scope functions (
let,apply,run) - Creates an extension property
- Demonstrates
withfor object configuration
Up Next
In the next lesson, you'll learn about Coroutines — async programming in Kotlin.
Related Topics
Frequently Asked Questions about Extensions
What is Extensions in Kotlin?
Extensions is a fundamental concept in Kotlin. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Extensions?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Extensions.
Why is Extensions important in Kotlin?
Extensions is essential for Kotlin development. Understanding this concept will help you write better code and solve real-world problems more effectively.