Junior — Middle
Can you explain the concept of extension functions in Kotlin?
sobes.tech AI
Answer from AI
Extension functions in Kotlin allow adding new functions to existing classes without the need for inheritance or modifying the original class code.
This is achieved through special syntax where the function is declared outside the class, but with a receiver type indicating the class it "extends".
Example of an extension function for the String class:
fun String.isPalindrome(): Boolean {
return this == this.reversed()
}
fun main() {
val word = "level"
println(word.isPalindrome()) // Outputs: true
}
Thus, extension functions enable writing more expressive and readable code by adding methods to classes, even if you do not have access to their source code.