Kotlin Extension Functions — Add Methods Without Inheriting
Extension functions let you add new functions to existing classes without inheriting from them or modifying their source code.
What You Will Learn
- Declare extension functions
- Use "this" in extension functions
- Extend built-in types like String and Int
- Understand extension function limitations
- Nullable receiver extensions
Declaring Extension Functions
Basic Extension Function
fun String.shout(): String = uppercase() + "!!!"
fun Int.isEven(): Boolean = this % 2 == 0
fun Int.square() = this * this
fun main() {
println("kotlin".shout())
println(4.isEven())
println(7.isEven())
println(5.square())
}String.shout() extends String. Inside the function, this refers to the receiver (the String). 4.isEven() is called on 4 as if it were a built-in method.
Extension Functions on Custom Classes
Extending a Custom Class
data class User(val name: String, val age: Int)
fun User.isAdult() = age >= 18
fun User.greeting() = "Hello, I am $name"
fun main() {
val user = User("Juned", 25)
println(user.isAdult())
println(user.greeting())
}isAdult and greeting are defined outside User but called as if they were methods of User. This keeps the User class clean.
Nullable Receiver Extensions
Nullable Extension
fun String?.orEmpty2(): String = this ?: ""
fun main() {
val a: String? = null
val b: String? = "Kotlin"
println(a.orEmpty2())
println(b.orEmpty2())
}The receiver type is String? so you can call this function on nullable strings without a safe call. Inside, this is used with ?: to provide an empty string fallback.
Practice Exercise
What prints? fun Int.doubled() = this * 2 fun main() { println(6.doubled()) }
Quick Quiz
Can an extension function access private members of the extended class?
Frequently Asked Questions
Related Tutorials
Written by KotlinGuide Editorial Team · Reviewed by KotlinGuide Technical Review