0
0
Kotlinprogramming~15 mins

Observable property delegation in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Observable Property Delegation in Kotlin
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Assign mood = "Excited" and then mood = "Calm" to see the messages.