Sobes.tech
Junior — Middle

How are extension functions implemented and used in Kotlin?

sobes.tech AI

Answer from AI

In Kotlin, extension functions allow you to add new functions to existing classes without the need for inheritance or modifying the original class code. They are declared outside the class using the syntax fun ReceiverType.functionName(). Inside an extension function, this refers to the receiver object.

Example:

fun String.lastChar(): Char = this[this.length - 1]

val c = "Kotlin".lastChar()  // 'n'

Extension functions are convenient for adding utilities and improving code readability, especially when working with library classes. They are called like regular object methods but are actually static functions with the first parameter being the receiver object.