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

Kotlin · Intermediate · question 38 of 100

How can you create a custom delegate for a property in Kotlin? Provide an example.?

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

In Kotlin, a delegate is an object that is responsible for providing the implementation for a property. It can be used to customize the behavior of a property in various ways. To create a custom delegate for a property, you need to define a class that implements the ‘ReadWriteProperty‘ or ‘ReadOnlyProperty‘ interface, depending on whether the property is mutable or not.

Here is an example of creating a custom delegate for a mutable property:

import kotlin.reflect.KProperty

class IncrementDelegate(var value: Int) {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): Int {
        return value
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: Int) {
        value += newValue
    }
}

class MyClass {
    var counter by IncrementDelegate(0)
}

fun main() {
    val obj = MyClass()
    obj.counter += 5
    println(obj.counter) // Output: 5
    obj.counter += 3
    println(obj.counter) // Output: 8
}

In the code above, we define a custom delegate called ‘IncrementDelegate‘ that takes an initial value for the property. It implements the ‘getValue‘ and ‘setValue‘ methods of the ‘ReadWriteProperty‘ interface to provide the behavior for getting and setting the property value.

We then define a class called ‘MyClass‘ that has a property called ‘counter‘ that is delegated to an instance of ‘IncrementDelegate‘. We can use the ‘counter‘ property as if it were a regular property, but any read or write operation is delegated to the ‘IncrementDelegate‘ object.

When we run the ‘main‘ function, we create an instance of ‘MyClass‘ and use the ‘counter‘ property to increment its value. The output shows that the custom delegate works correctly and the property value is updated as expected.

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