Kotlin Extensions

Add new functionality to existing classes without inheritance

🔧 What are Kotlin Extensions?

Extension functions allow you to add new functionality to existing classes without modifying their source code. They're like adding superpowers to classes you can't change directly.


// Add a function to String class
fun String.isEmail(): Boolean {
    return this.contains("@") && this.contains(".")
}

// Usage
val email = "[email protected]"
println(email.isEmail()) // true
                                    

Types of Extensions

Extension Functions

Add new methods to existing classes

fun Int.isEven(): Boolean = this % 2 == 0
📦

Extension Properties

Add computed properties to classes

val String.wordCount: Int
    get() = this.split(" ").size
🎯

Nullable Extensions

Extend nullable types safely

fun String?.isNullOrEmpty(): Boolean = 
    this == null || this.isEmpty()
🏗️

Generic Extensions

Work with any type using generics

fun  T.println(): T {
    println(this)
    return this
}

🔹 Basic Extension Functions

Create your first extension function:

// Extend String class
fun String.removeSpaces(): String {
    return this.replace(" ", "")
}

// Extend Int class
fun Int.squared(): Int {
    return this * this
}

// Usage examples
fun main() {
    val text = "Hello World"
    println(text.removeSpaces()) // "HelloWorld"
    
    val number = 5
    println(number.squared()) // 25
}

Output:

HelloWorld

25

🔹 Extension Properties

Add computed properties to existing classes:

// Extension property for String
val String.lastChar: Char
    get() = this[this.length - 1]

// Extension property for List
val  List.secondOrNull: T?
    get() = if (this.size >= 2) this[1] else null

// Usage
fun main() {
    val name = "Kotlin"
    println("Last character: ${name.lastChar}") // n
    
    val numbers = listOf(1, 2, 3, 4, 5)
    println("Second element: ${numbers.secondOrNull}") // 2
}

Output:

Last character: n

Second element: 2

🔹 Practical Examples

Real-world extension functions:

// Date formatting extension
fun Long.toDateString(): String {
    val date = java.util.Date(this)
    val format = java.text.SimpleDateFormat("yyyy-MM-dd")
    return format.format(date)
}

// Collection utilities
fun  List.second(): T = this[1]
fun  List.secondOrNull(): T? = if (size >= 2) this[1] else null

// String validation
fun String.isValidEmail(): Boolean {
    return this.matches(Regex("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}"))
}

// Usage
fun main() {
    val timestamp = System.currentTimeMillis()
    println("Date: ${timestamp.toDateString()}")
    
    val fruits = listOf("apple", "banana", "cherry")
    println("Second fruit: ${fruits.second()}")
    
    val email = "[email protected]"
    println("Valid email: ${email.isValidEmail()}")
}

🧠 Test Your Knowledge

What keyword is used to create extension functions in Kotlin?