Kotlin Extension Functions and Properties Tutorial: Extending Classes Without Inheritance


This Kotlin Extension Functions and Properties tutorial explains how to extend existing classes with new functions and properties without modifying their source code or using inheritance. It covers creating extension functions, extension properties, real-world examples, and best practices to help developers write clean, reusable, and expressive Kotlin code.

Kotlin Extension Functions and Properties – Complete Tutorial

What Are Extension Functions?

Extension functions allow you to add new functions to existing classes without changing their source code or inheriting from them. They are resolved at compile time.

Creating Extension Functions

Syntax


fun ClassName.functionName() {
// function body
}

Example: String Extension Function


fun String.addExclamation(): String {
return this + "!"
}

fun main() {
val message = "Hello Kotlin"
println(message.addExclamation())
}

Example: Int Extension Function


fun Int.isEven(): Boolean {
return this % 2 == 0
}

fun main() {
println(10.isEven()) // true
println(7.isEven()) // false
}

Best Practices for Extension Functions

  1. Use extensions to improve readability and expressiveness.
  2. Keep extension functions small and focused.
  3. Avoid adding extensions that change expected behavior.

Extension Properties

Extension properties allow adding properties to existing classes. They cannot store state; they only provide getters (and setters if mutable).

Syntax


val ClassName.propertyName: Type
get() = ...

Example: String Extension Property


val String.wordCount: Int
get() = this.trim().split("\\s+".toRegex()).size

fun main() {
val text = "Kotlin is powerful"
println(text.wordCount) // 3
}

Example: List Extension Property


val <T> List<T>.lastIndex: Int
get() = this.size - 1

fun main() {
val list = listOf(10, 20, 30)
println(list.lastIndex) // 2
}

Best Practices for Extension Properties

  1. Use extension properties for computed values only.
  2. Avoid naming conflicts with existing class members.
  3. Prefer properties when no parameters are required.

Real-World Use Case


fun String.isValidEmail(): Boolean {
return this.contains("@") && this.contains(".")
}

fun main() {
val email = "test@example.com"
println(email.isValidEmail()) // true
}

Key Points to Remember

  1. Extension functions do not actually modify the class.
  2. They are statically resolved at compile time.
  3. Member functions always take precedence over extensions.

Summary

This chapter explained how to create and use extension functions and extension properties in Kotlin. These features allow developers to write cleaner, more expressive code by extending existing classes safely and efficiently without inheritance.