0
0
Kotlinprogramming~10 mins

Custom delegated properties in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Aby
Bwith
Cusing
Dfrom
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'with' or 'from' instead of 'by' causes syntax errors.
Forgetting the keyword entirely.
2fill in blank
medium

Complete 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'
Ayield
Bprint
Creturn
Dthrow
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'print' instead of 'return' does not provide the value.
Using 'throw' causes an exception.
3fill in blank
hard

Fix 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'
Aproperty
BstoredValue
Cfield
DthisRef
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to assign to 'property' or 'thisRef' causes errors.
Using 'field' outside of property setter is invalid.
4fill in blank
hard

Fill 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'
AstoredValue
Bvalue
Dproperty
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.
5fill in blank
hard

Fill 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'
AstoredValue
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'value' as a variable name for storage causes confusion.
Forgetting to return the stored value in getValue.