0Pricing
Android Academy · Lesson

Extension Functions & Higher-Order Functions

Add behavior to existing types with extension functions and use higher-order functions and scope functions (let, apply, also, run, with) for expressive Kotlin code.

Extension Functions

An extension function lets you add new functions to existing classes without modifying them or using inheritance. You can extend String, Int, your own classes, or even Android's View.

Syntax: fun TypeName.functionName() { }

Writing Extension Functions

Inside an extension function, this refers to the receiver object:

fun String.isPalindrome(): Boolean {
    val cleaned = this.lowercase().filter { it.isLetter() }
    return cleaned == cleaned.reversed()
}

fun Int.isEven() = this % 2 == 0

fun main() {
    println("racecar".isPalindrome())  // true
    println("hello".isPalindrome())    // false
    println(4.isEven())                // true
    println(7.isEven())                // false
}

All lessons in this course

  1. Null Safety
  2. Classes & Objects
  3. Data Classes & Sealed Classes
  4. Extension Functions & Higher-Order Functions
← Back to Android Academy