0
0
Kotlinprogramming~10 mins

Custom getters and setters 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 define a custom getter that returns the name in uppercase.

Kotlin
class Person(val name: String) {
    val upperName: String
        get() = [1]
}
Drag options to blanks, or click blank then click option'
Aname.lowercase()
Bname.uppercase()
Cname.length
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase() instead of uppercase()
Returning the original name without conversion
2fill in blank
medium

Complete the code to define a custom setter that sets the age only if it is positive.

Kotlin
class Person {
    var age: Int = 0
        set(value) {
            if ([1]) field = value
        }
}
Drag options to blanks, or click blank then click option'
Avalue > 0
Bvalue < 0
Cvalue == 0
Dvalue >= 0
Attempts:
3 left
💡 Hint
Common Mistakes
Using value < 0 which allows negative ages
Using value >= 0 which allows zero age
3fill in blank
hard

Fix the error in the custom setter to avoid infinite recursion.

Kotlin
class Rectangle {
    var width: Int = 0
        set(value) {
            [1] = value
        }
}
Drag options to blanks, or click blank then click option'
Afield
Bwidth
Cthis.width
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning to the property name instead of field
Using this.width which also calls the setter
4fill in blank
hard

Fill both blanks to create a custom getter that returns the area of the rectangle.

Kotlin
class Rectangle(val height: Int, val width: Int) {
    val area: Int
        get() = [1] * [2]
}
Drag options to blanks, or click blank then click option'
Aheight
Bwidth
Carea
Dthis
Attempts:
3 left
💡 Hint
Common Mistakes
Using area inside its own getter causing recursion
Using this which is not a number
5fill in blank
hard

Fill all three blanks to create a property with a custom getter and setter that keeps the score between 0 and 100.

Kotlin
class Game {
    var score: Int = 0
        get() = [1]
        set(value) {
            field = when {
                value < 0 -> [2]
                value > 100 -> [3]
                else -> value
            }
        }
}
Drag options to blanks, or click blank then click option'
Afield
B0
C100
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Getter returning value instead of field
Setter not clamping values correctly