📖 Scenario: Imagine you are creating a simple app that tracks a person's mood. You want to know whenever the mood changes so you can show a message or take action.
🎯 Goal: Build a Kotlin program that uses observable property delegation to watch changes in a person's mood and print a message every time the mood changes.
📋 What You'll Learn
Create a variable with observable property delegation
Use a lambda to react to changes in the property
Print a message showing the old and new mood values
💡 Why This Matters
🌍 Real World
Observable properties are useful in apps where you want to track changes and update the UI or perform actions automatically.
💼 Career
Many Kotlin developers use property delegation to write cleaner and more reactive code, especially in Android app development.
Progress0 / 4 steps
1
Create a mood variable
Create a var called mood of type String and set its initial value to "Happy".
Kotlin
Hint
Use var mood: String = "Happy" to create the variable.
2
Add observable property delegation
Import kotlin.properties.Delegates and change the mood variable to use Delegates.observable with initial value "Happy".
Kotlin
Hint
Use var mood: String by Delegates.observable("Happy") { prop, old, new -> }.
3
Add reaction to mood changes
Inside the observable lambda, add a println statement that prints: "Mood changed from $old to $new".
Kotlin
Hint
Use println("Mood changed from $old to $new") inside the lambda.
4
Change mood and print output
Change the value of mood to "Excited" and then to "Calm". This should print the mood change messages.
Kotlin
Hint
Assign mood = "Excited" and then mood = "Calm" to see the messages.
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
Step 1: Understand observable delegation purpose
Observable delegation lets you watch a property for changes and react when it changes.
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.
Final Answer:
It watches a property and runs code when the property value changes. -> Option D
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
Step 1: Recall observable property syntax
Observable properties use by observable(initialValue) { prop, old, new -> ... } with var.
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.
Final Answer:
var name: String by observable("") { prop, old, new -> println("Changed") } -> Option A
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
Step 1: Understand observable callback calls
The observable lambda runs every time the property changes, printing old and new values.
Step 2: Trace property changes in main()
Initially name is "Unknown". First change to "Alice" triggers print. Second change to "Bob" triggers print again.
Final Answer:
Name changed from Unknown to Alice
Name changed from Alice to Bob -> Option C
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
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.
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.
Final Answer:
Logical error: observable does not prevent count from decreasing. -> Option A
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
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.
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.
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
Quick Check:
Use correct formula and update fahrenheit in celsius observable [OK]
Hint: Use correct formula and update dependent property inside observable [OK]