Junior — Middle
Can you explain what an extension function is in programming?
sobes.tech AI
Answer from AI
An extension function is a way to add a new function to an existing class without inheriting from it or modifying its source code. In Kotlin, for example, you can define an extension function that can be called as if it were part of the class.
Example in Kotlin:
fun String.lastChar(): Char = this[this.length - 1]
val c = "Hello".lastChar() // 'o'
Here, we added a lastChar() function to the String class. This is convenient for improving readability and extending functionality without creating subclasses.