Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a delegated property using the 'by' keyword.
Kotlin
val myValue: String [1] MyDelegate() Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'with' or 'from' instead of 'by' causes syntax errors.
Forgetting the keyword entirely.
✗ Incorrect
In Kotlin, delegated properties use the 'by' keyword to delegate the property implementation to another object.
2fill in blank
mediumComplete the operator function to get the value of the delegated property.
Kotlin
operator fun getValue(thisRef: Any?, property: KProperty<*>): String [1] "Hello from delegate"
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'print' instead of 'return' does not provide the value.
Using 'throw' causes an exception.
✗ Incorrect
The 'getValue' operator function must return the value of the property, so it uses 'return'.
3fill in blank
hardFix the error in the setValue operator function to correctly assign the new value.
Kotlin
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
[1] = value
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to assign to 'property' or 'thisRef' causes errors.
Using 'field' outside of property setter is invalid.
✗ Incorrect
The delegate must assign the new value to its own storage variable, here named 'storedValue'.
4fill in blank
hardFill both blanks to create a delegate that stores and returns an integer value.
Kotlin
class IntDelegate { private var [1] = 0 operator fun getValue(thisRef: Any?, property: KProperty<*>): Int = [2] }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'value' in getValue is incorrect because it's not defined there.
Using 'property' as a value causes errors.
✗ Incorrect
The delegate uses 'storedValue' to keep the integer and returns it in getValue.
5fill in blank
hardFill all three blanks to complete a delegate that logs and stores a string property.
Kotlin
class LoggingDelegate { private var [1] = "" operator fun getValue(thisRef: Any?, property: KProperty<*>): String { println("Getting value of ${property.name}") return [2] } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) { println("Setting value of ${property.name} to $value") [3] = value } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'value' as a variable name for storage causes confusion.
Forgetting to return the stored value in getValue.
✗ Incorrect
The delegate uses 'storedValue' to keep the string, returns it in getValue, and assigns it in setValue.