WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Kotlin · Basic · question 6 of 100

What are extension functions in Kotlin? Provide an example.?

📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

Extension functions in Kotlin are a way to add new behavior or functionality to an existing class without having to modify the class itself. They allow for concise and readable code by enabling developers to define methods that can be called on a particular type, even if that type was not originally designed to support those methods.

Extension functions are created by defining a function outside of a class or interface, but prefixing the function name with the class or interface type that it extends. When the function is called on an instance of that type, it behaves as if it were a member function of the class or interface.

Here is an example of an extension function for the ‘String‘ class:

fun String.isPalindrome(): Boolean {
    val reversed = this.reversed()
    return this == reversed
}

This extension function adds a ‘isPalindrome()‘ method to the ‘String‘ class, allowing us to check if a string is a palindrome. We can call the function on any instance of the ‘String‘ class, like this:

val palindrome = "racecar"
val notPalindrome = "hello"

println(palindrome.isPalindrome()) // true
println(notPalindrome.isPalindrome()) // false

In the above example, we create an extension function ‘isPalindrome‘ that utilizes the existing ‘reversed()‘ method to check if a ‘String‘ instance is a palindrome or not. By adding this extension function, we are able to call it on any ‘String‘ instance and receive a simple and reusable answer to whether or not the ‘String‘ is a palindrome.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Kotlin interview — then scores it.
📞 Practice Kotlin — free 15 min
📕 Buy this interview preparation book: 100 Kotlin questions & answers — PDF + EPUB for $5

All 100 Kotlin questions · All topics