Bird
Raised Fist0
Kotlinprogramming~20 mins

Observable property delegation in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Observable Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Kotlin code using observable delegation?
Consider the following Kotlin code that uses observable property delegation. What will be printed when the code runs?
Kotlin
import kotlin.properties.Delegates

class User {
    var name: String by Delegates.observable("Unknown") { prop, old, new ->
        println("Property '${prop.name}' changed from '$old' to '$new'")
    }
}

fun main() {
    val user = User()
    user.name = "Alice"
    user.name = "Bob"
}
AProperty 'name' changed from 'Unknown' to 'Bob'
BProperty 'name' changed from 'Alice' to 'Bob'
C
Property 'name' changed from 'Unknown' to 'Alice'
Property 'name' changed from 'Alice' to 'Bob'
DNo output
Attempts:
2 left
💡 Hint
Think about how observable delegation calls the callback on every property change.
🧠 Conceptual
intermediate
1:30remaining
What is the main purpose of observable property delegation in Kotlin?
Why would a Kotlin developer use observable property delegation?
ATo automatically run code whenever a property value changes
BTo make a property immutable
CTo delay the initialization of a property until first use
DTo create a property that cannot be accessed outside the class
Attempts:
2 left
💡 Hint
Think about what happens when a property changes.
🔧 Debug
advanced
2:30remaining
Why does this Kotlin code using observable delegation cause a stack overflow?
Examine the code below. Why does it cause a stack overflow error when run?
Kotlin
import kotlin.properties.Delegates

class Counter {
    var count: Int by Delegates.observable(0) { _, _, new ->
        if (new < 10) {
            count = new + 1
        }
    }
}

fun main() {
    val counter = Counter()
    counter.count = 1
    println(counter.count)
}
ABecause the println statement is inside the observable callback
BBecause the initial value 0 is invalid for observable properties
CBecause the property count is immutable and cannot be changed
DBecause the observable callback modifies the property it observes, causing infinite recursion
Attempts:
2 left
💡 Hint
Think about what happens when the property is changed inside its own observer.
📝 Syntax
advanced
1:30remaining
Which option correctly declares an observable property in Kotlin?
Select the correct Kotlin syntax to declare an observable property 'score' initialized to 0 that prints changes.
Avar score: Int = Delegates.observable(0) { prop, old, new -> println("Score changed from ${old} to ${new}") }
Bvar score: Int by Delegates.observable(0) { prop, old, new -> println("Score changed from ${old} to ${new}") }
Cval score: Int by Delegates.observable(0) { prop, old, new -> println("Score changed from ${old} to ${new}") }
Dvar score: Int by observable(0) { prop, old, new -> println("Score changed from ${old} to ${new}") }
Attempts:
2 left
💡 Hint
Remember the correct syntax for property delegation uses 'by' and the delegate object.
🚀 Application
expert
2:30remaining
How many times will the observable callback run in this Kotlin code?
Given the code below, how many times will the observable callback print a message?
Kotlin
import kotlin.properties.Delegates

class Temperature {
    var celsius: Int by Delegates.observable(20) { _, old, new ->
        println("Temperature changed from ${old} to ${new}")
    }
}

fun main() {
    val temp = Temperature()
    temp.celsius = 25
    temp.celsius = 25
    temp.celsius = 30
}
A2
B1
C0
D3
Attempts:
2 left
💡 Hint
Consider if setting the same value triggers the observable callback.

Practice

(1/5)
1. What does observable property delegation in Kotlin do?
easy
A. It delays the initialization of a property until first use.
B. It makes a property immutable and unchangeable.
C. It automatically converts a property to a string.
D. It watches a property and runs code when the property value changes.

Solution

  1. Step 1: Understand observable delegation purpose

    Observable delegation lets you watch a property for changes and react when it changes.
  2. Step 2: Compare options with definition

    Only It watches a property and runs code when the property value changes. describes this behavior correctly; others describe different Kotlin features.
  3. Final Answer:

    It watches a property and runs code when the property value changes. -> Option D
  4. Quick Check:

    Observable delegation = watch property changes [OK]
Hint: Observable runs code on property change, not on initialization [OK]
Common Mistakes:
  • Confusing observable with lazy initialization
  • Thinking observable makes property immutable
  • Assuming observable converts types automatically
2. Which of the following is the correct syntax to declare an observable property in Kotlin?
easy
A. var name: String by observable("") { prop, old, new -> println("Changed") }
B. var name: String = observable("") { prop, old, new -> println("Changed") }
C. val name: String by observable("") { prop, old, new -> println("Changed") }
D. var name: String observable("") { prop, old, new -> println("Changed") }

Solution

  1. Step 1: Recall observable property syntax

    Observable properties use by observable(initialValue) { prop, old, new -> ... } with var.
  2. Step 2: Check each option

    var name: String by observable("") { prop, old, new -> println("Changed") } matches correct syntax. var name: String = observable("") { prop, old, new -> println("Changed") } uses wrong assignment. val name: String by observable("") { prop, old, new -> println("Changed") } uses val which is immutable. var name: String observable("") { prop, old, new -> println("Changed") } misses by.
  3. Final Answer:

    var name: String by observable("") { prop, old, new -> println("Changed") } -> Option A
  4. Quick Check:

    Use 'var' and 'by observable' syntax [OK]
Hint: Use 'var' with 'by observable' and initial value [OK]
Common Mistakes:
  • Using val instead of var for observable
  • Omitting 'by' keyword
  • Assigning observable without 'by'
3. What will be the output of this Kotlin code?
import kotlin.properties.Delegates

class User {
    var name: String by Delegates.observable("Unknown") { prop, old, new ->
        println("Name changed from $old to $new")
    }
}

fun main() {
    val user = User()
    user.name = "Alice"
    user.name = "Bob"
}
medium
A. Name changed from Unknown to Alice
B. Name changed from Alice to Bob
C. Name changed from Unknown to Alice Name changed from Alice to Bob
D. No output

Solution

  1. Step 1: Understand observable callback calls

    The observable lambda runs every time the property changes, printing old and new values.
  2. Step 2: Trace property changes in main()

    Initially name is "Unknown". First change to "Alice" triggers print. Second change to "Bob" triggers print again.
  3. Final Answer:

    Name changed from Unknown to Alice Name changed from Alice to Bob -> Option C
  4. Quick Check:

    Observable prints on each change [OK]
Hint: Observable prints on every property change [OK]
Common Mistakes:
  • Thinking only last change triggers print
  • Ignoring initial value in output
  • Expecting output without property change
4. Identify the error in this Kotlin code using observable delegation:
import kotlin.properties.Delegates

class Counter {
    var count: Int by Delegates.observable(0) { prop, old, new ->
        if (new < old) {
            println("Count cannot decrease")
        }
    }
}

fun main() {
    val c = Counter()
    c.count = 5
    c.count = 3
}
medium
A. Logical error: observable does not prevent count from decreasing.
B. Syntax error: '<' should be '<' without escaping.
C. Runtime error: observable lambda cannot have if statements.
D. No error; code works as expected printing a warning when count decreases.

Solution

  1. Step 1: Check syntax and runtime correctness

    The code syntax is correct; escaped '<' is valid in HTML but in code it should be '<'. Assuming code runs, no syntax error.
  2. Step 2: Analyze observable behavior

    The observable lambda prints a message if count decreases but does not stop the change. So count can decrease despite warning.
  3. Final Answer:

    Logical error: observable does not prevent count from decreasing. -> Option A
  4. Quick Check:

    Observable reacts but does not block changes [OK]
Hint: Observable warns but doesn't stop changes automatically [OK]
Common Mistakes:
  • Expecting observable to block property changes
  • Confusing HTML escape with Kotlin syntax
  • Thinking if statement causes runtime error
5. You want to create a Kotlin class Temperature with an observable property celsius. When celsius changes, it should update another property fahrenheit automatically. Which code correctly implements this behavior?
hard
A. class Temperature { var celsius: Double = 0.0 var fahrenheit: Double by Delegates.observable(32.0) { _, _, new -> celsius = (new - 32) * 5 / 9 } }
B. class Temperature { var celsius: Double by Delegates.observable(0.0) { _, _, new -> fahrenheit = new * 9 / 5 + 32 } var fahrenheit: Double = 32.0 }
C. class Temperature { var celsius: Double by Delegates.observable(0.0) { _, _, new -> fahrenheit = new + 32 } var fahrenheit: Double = 32.0 }
D. class Temperature { var celsius: Double by Delegates.observable(0.0) { _, _, new -> fahrenheit = new * 5 / 9 + 32 } var fahrenheit: Double = 32.0 }

Solution

  1. Step 1: Understand temperature conversion formulas

    Fahrenheit = Celsius * 9/5 + 32. class Temperature { var celsius: Double by Delegates.observable(0.0) { _, _, new -> fahrenheit = new * 9 / 5 + 32 } var fahrenheit: Double = 32.0 } uses this formula correctly.
  2. Step 2: Check observable updates fahrenheit on celsius change

    class Temperature { var celsius: Double by Delegates.observable(0.0) { _, _, new -> fahrenheit = new * 9 / 5 + 32 } var fahrenheit: Double = 32.0 } updates fahrenheit inside observable lambda of celsius, which is correct behavior.
  3. Final Answer:

    class Temperature { var celsius: Double by Delegates.observable(0.0) { _, _, new -> fahrenheit = new * 9 / 5 + 32 } var fahrenheit: Double = 32.0 } -> Option B
  4. Quick Check:

    Use correct formula and update fahrenheit in celsius observable [OK]
Hint: Use correct formula and update dependent property inside observable [OK]
Common Mistakes:
  • Using wrong temperature conversion formula
  • Updating celsius inside fahrenheit observable causing infinite loop
  • Adding instead of multiplying in formula
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