0
0
Kotlinprogramming~20 mins

Custom delegated properties in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Custom Delegate Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple custom delegate
What is the output of this Kotlin code using a custom delegated property?
Kotlin
import kotlin.reflect.KProperty

class Delegate {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return "Hello from delegate"
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        println("Setting value to '$value'")
    }
}

class Example {
    var p: String by Delegate()
}

fun main() {
    val e = Example()
    println(e.p)
    e.p = "New Value"
}
A
Hello from delegate
Setting value to 'New Value'
B
Hello from delegate
New Value
C
Setting value to 'New Value'
Hello from delegate
D
Hello from delegate
Setting value to 'p'
Attempts:
2 left
💡 Hint
Remember that the setValue prints a message, and getValue returns a fixed string.
Predict Output
intermediate
2:00remaining
Behavior of a delegate with backing field
What will be printed when running this Kotlin code with a custom delegate that stores a value internally?
Kotlin
import kotlin.reflect.KProperty

class StorageDelegate {
    private var storedValue: Int = 0

    operator fun getValue(thisRef: Any?, property: KProperty<*>): Int {
        return storedValue
    }

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

class Counter {
    var count: Int by StorageDelegate()
}

fun main() {
    val c = Counter()
    c.count = 10
    println(c.count)
    c.count = 20
    println(c.count)
}
A
10
10
B
0
0
C
10
20
D
20
20
Attempts:
2 left
💡 Hint
The delegate stores the value internally and returns it on get.
🔧 Debug
advanced
2:00remaining
Identify the error in this custom delegate code
This Kotlin code tries to create a custom delegate but fails. What error does it produce when compiled?
Kotlin
class BadDelegate {
    operator fun getValue(thisRef: Any, property: kotlin.reflect.KProperty<*>): String {
        return "value"
    }

    operator fun setValue(thisRef: Any, property: kotlin.reflect.KProperty<*>, value: Int) {
        // do nothing
    }
}

class Test {
    var prop: String by BadDelegate()
}

fun main() {
    val t = Test()
    println(t.prop)
    t.prop = "new"
}
AUnresolved reference: BadDelegate
BType mismatch: setValue expects Int but assigned String
CNo error, prints 'value' and ignores assignment
DProperty delegate must be immutable
Attempts:
2 left
💡 Hint
Check the types used in setValue compared to the property type.
🧠 Conceptual
advanced
2:00remaining
Understanding lazy initialization with custom delegate
Consider this Kotlin custom delegate for lazy initialization. What will be the output when main runs?
Kotlin
class LazyDelegate<T>(val initializer: () -> T) {
    private var value: T? = null

    operator fun getValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>): T {
        if (value == null) {
            value = initializer()
            println("Initialized")
        }
        return value!!
    }
}

class Example {
    val lazyValue: String by LazyDelegate { "Hello" }
}

fun main() {
    val e = Example()
    println(e.lazyValue)
    println(e.lazyValue)
}
A
Initialized
Initialized
Hello
Hello
B
Hello
Hello
C
Hello
Initialized
Hello
D
Initialized
Hello
Hello
Attempts:
2 left
💡 Hint
The initializer runs only once when value is null.
Predict Output
expert
3:00remaining
Custom delegate with observable behavior
What is the output of this Kotlin program using a custom delegate that observes changes?
Kotlin
import kotlin.reflect.KProperty

class ObservableDelegate<T>(var value: T, val onChange: (old: T, new: T) -> Unit) {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): T = value

    operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: T) {
        val oldValue = value
        value = newValue
        if (oldValue != newValue) {
            onChange(oldValue, newValue)
        }
    }
}

class Person {
    var name: String by ObservableDelegate("Unknown") { old, new ->
        println("Name changed from $old to $new")
    }
}

fun main() {
    val p = Person()
    println(p.name)
    p.name = "Alice"
    p.name = "Alice"
    p.name = "Bob"
}
A
Unknown
Name changed from Unknown to Alice
Name changed from Alice to Bob
B
Unknown
Name changed from Unknown to Alice
Name changed from Alice to Alice
Name changed from Alice to Bob
C
Name changed from Unknown to Alice
Name changed from Alice to Bob
Unknown
D
Unknown
Name changed from Unknown to Alice
Name changed from Alice to Bob
Bob
Attempts:
2 left
💡 Hint
The onChange callback triggers only when the new value differs from the old.