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

Kotlin · Advanced · question 45 of 100

How can you create an extension property in Kotlin? Provide an example.?

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

In Kotlin, we can create an extension property just like we create extension functions. An extension property is a property that can be added to an existing class without actually modifying the class itself.

Here’s an example of creating an extension property for the ‘String‘ class:

// Define the extension property
val String.customLength: Int
    get() = this.length + 5

// Use the extension property on a String instance
fun main() {
    val str = "hello"
    println(str.customLength) // Output: 10
}

In the above code, we have created an extension property called ‘customLength‘ for the ‘String‘ class. This extension property adds 5 to the length of the string and returns the result.

To define an extension property, we need to prefix the property name with the class name and use the ‘val‘ or ‘var‘ keyword to specify if the property is read-only or mutable, respectively. The implementation of the property is defined in its getter function, which is accessed using the ‘get()‘ method.

In the ‘main‘ function, we have created a ‘String‘ instance named ‘str‘ and accessed the ‘customLength‘ property on it. The output of this property call is 10, which is the length of the string "hello" plus 5.

Overall, extension properties in Kotlin provide a convenient way to add new properties to existing classes and extend their functionality without modifying those classes directly.

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