Bird
Raised Fist0
Kotlinprogramming~20 mins

Custom delegated properties in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using custom delegated properties in Kotlin?
easy
A. To define extension functions for a class
B. To create multiple constructors for a class
C. To control how a property's value is stored and retrieved
D. To override the default toString() method

Solution

  1. Step 1: Understand property delegation concept

    Delegated properties let you customize how a property's value is handled behind the scenes.
  2. Step 2: Identify the purpose of custom delegation

    Custom delegated properties specifically allow control over getting and setting property values.
  3. Final Answer:

    To control how a property's value is stored and retrieved -> Option C
  4. Quick Check:

    Custom delegation = control property access [OK]
Hint: Delegation controls property get/set behavior [OK]
Common Mistakes:
  • Confusing delegation with constructors
  • Thinking delegation defines functions
  • Mixing delegation with method overriding
2. Which of the following is the correct syntax to declare a custom delegated property in Kotlin?
easy
A. val prop = Delegate()
B. val prop by Delegate()
C. val prop: Delegate by this
D. val prop delegate Delegate()

Solution

  1. Step 1: Recall Kotlin delegation syntax

    Delegated properties use the by keyword followed by a delegate instance.
  2. Step 2: Match correct syntax

    val prop by Delegate() correctly declares a delegated property.
  3. Final Answer:

    val prop by Delegate() -> Option B
  4. Quick Check:

    Delegation uses 'by' keyword [OK]
Hint: Look for 'by' keyword with delegate instance [OK]
Common Mistakes:
  • Using '=' instead of 'by' for delegation
  • Incorrect delegate type declaration
  • Missing parentheses for delegate constructor
3. What will be the output of the following Kotlin code?
class Delegate {
    operator fun getValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>): String {
        return "Hello from delegate"
    }
}

class Example {
    val message: String by Delegate()
}

fun main() {
    val e = Example()
    println(e.message)
}
medium
A. Hello from delegate
B. null
C. Compilation error
D. Hello from Example

Solution

  1. Step 1: Understand getValue operator

    The getValue function returns the string "Hello from delegate" when the property is accessed.
  2. Step 2: Trace property access in main()

    Accessing e.message calls getValue and prints the returned string.
  3. Final Answer:

    Hello from delegate -> Option A
  4. Quick Check:

    Delegate getValue returns string [OK]
Hint: getValue defines returned property value [OK]
Common Mistakes:
  • Expecting default property value instead of delegate's
  • Confusing getValue with setValue
  • Assuming compilation error due to missing parameters
4. Identify the error in this Kotlin code using a custom delegated property:
class Delegate {
    operator fun getValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>): Int {
        return 42
    }
}

class Example {
    var number: Int by Delegate()
}

fun main() {
    val e = Example()
    e.number = 10
    println(e.number)
}
medium
A. Delegate class must be an interface
B. Property number should be val, not var
C. getValue must return String, not Int
D. Delegate class lacks setValue operator function

Solution

  1. Step 1: Check property mutability and delegation

    The property number is var, so delegate must support both get and set.
  2. Step 2: Verify delegate methods

    The Delegate class only defines getValue, missing setValue needed for var.
  3. Final Answer:

    Delegate class lacks setValue operator function -> Option D
  4. Quick Check:

    var needs getValue and setValue [OK]
Hint: var properties need both getValue and setValue [OK]
Common Mistakes:
  • Forgetting setValue for var properties
  • Assuming getValue return type must be String
  • Thinking delegate must be interface
5. You want to create a custom delegated property that logs every time the property is read or written. Which of the following delegate implementations correctly achieves this?
class LoggingDelegate<T>(var value: T) {
    operator fun getValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>): T {
        println("Getting value of ${property.name}")
        return value
    }

    operator fun setValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>, newValue: T) {
        println("Setting value of ${property.name} to $newValue")
        value = newValue
    }
}

class Example {
    var data: String by LoggingDelegate("initial")
}

fun main() {
    val e = Example()
    e.data = "new"
    println(e.data)
}
hard
A. Logs on get and set, prints 'Setting value of data to new' then 'Getting value of data' and 'new'
B. Only logs on get, no output on set
C. Throws error because delegate class is not generic
D. Does not compile due to missing constructor parameters

Solution

  1. Step 1: Analyze delegate methods

    The delegate defines getValue and setValue with print statements logging property access.
  2. Step 2: Trace main function output

    Setting e.data = "new" prints setting log, then printing e.data triggers get log and prints value.
  3. Final Answer:

    Logs on get and set, prints 'Setting value of data to new' then 'Getting value of data' and 'new' -> Option A
  4. Quick Check:

    Delegate logs on get/set correctly [OK]
Hint: Check both getValue and setValue print logs [OK]
Common Mistakes:
  • Missing setValue causes no set logging
  • Assuming delegate must be non-generic
  • Forgetting to pass initial value to delegate
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard