0
0
Kotlinprogramming~30 mins

Custom delegated properties in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom Delegated Properties in Kotlin
📖 Scenario: You are building a simple Kotlin program to manage a user's profile settings. You want to control how certain properties behave when accessed or changed.
🎯 Goal: Create a custom delegated property that logs every time a property is read or written. Then use this delegate for a user's name property.
📋 What You'll Learn
Create a class called LoggingDelegate that implements the getValue and setValue operator functions.
The delegate should print a message when the property is read and when it is written.
Create a class called User with a property name that uses LoggingDelegate.
Create an instance of User, set the name property, then read it and print the value.
💡 Why This Matters
🌍 Real World
Custom delegated properties help manage how data is accessed or changed, useful in settings, caching, or validation.
💼 Career
Understanding Kotlin delegates is valuable for Android developers and Kotlin backend developers to write clean, reusable, and maintainable code.
Progress0 / 4 steps
1
Create the LoggingDelegate class
Create a class called LoggingDelegate with a mutable property value of type String initialized to an empty string.
Kotlin
Need a hint?

Use var value: String = "" inside the class to hold the property value.

2
Add getValue and setValue operator functions
Inside the LoggingDelegate class, add the operator fun getValue and operator fun setValue functions. In getValue, print "Getting value" and return value. In setValue, print "Setting value to" followed by the new value, then update value.
Kotlin
Need a hint?

Remember to use operator fun getValue(thisRef: Any?, property: KProperty<*>) and operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: String).

3
Create User class with name property using delegate
Create a class called User with a property name of type String that uses LoggingDelegate() as its delegate.
Kotlin
Need a hint?

Use var name: String by LoggingDelegate() inside the User class.

4
Create User instance, set and get name, then print it
Create a variable user as an instance of User. Set user.name to "Alice". Then print user.name.
Kotlin
Need a hint?

Remember to create val user = User(), then user.name = "Alice", and finally println(user.name).