0
0
Kotlinprogramming~10 mins

Properties with val and var 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 read-only property.

Kotlin
class Person {
    val name: String = [1]
}
Drag options to blanks, or click blank then click option'
Aval
Bvar
Cfun
D"Alice"
Attempts:
3 left
💡 Hint
Common Mistakes
Using var instead of a value for assignment.
Forgetting to use quotes for string values.
2fill in blank
medium

Complete the code to declare a mutable property.

Kotlin
class Car {
    var speed: Int = [1]
}
Drag options to blanks, or click blank then click option'
A0
B"fast"
Cval
Dfun
Attempts:
3 left
💡 Hint
Common Mistakes
Assigning a string to an integer property.
Using val instead of var for mutable properties.
3fill in blank
hard

Fix the error in the property declaration to make it mutable.

Kotlin
class Book {
    [1] title: String = "Kotlin Guide"
}
Drag options to blanks, or click blank then click option'
Afun
Bvar
Cval
Dconst
Attempts:
3 left
💡 Hint
Common Mistakes
Using val which makes the property read-only.
Using fun which is for functions, not properties.
4fill in blank
hard

Fill both blanks to declare a read-only property with a custom getter.

Kotlin
class Circle(val radius: Double) {
    val area: Double
        get() = [1] * radius [2] radius
}
Drag options to blanks, or click blank then click option'
AMath.PI
B*
C+
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of multiplication for squaring.
Using val inside the getter instead of a value.
5fill in blank
hard

Fill all three blanks to declare a mutable property with a backing field and custom setter.

Kotlin
class Temperature {
    var celsius: Double = [1]
        set(value) {
            field = if (value [2] [3]273.15) [3]273.15 else value
        }
}
Drag options to blanks, or click blank then click option'
A0.0
B<
C+
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using addition instead of subtraction for negative numbers.
Not using the backing field field inside the setter.