Challenge - 5 Problems
Kotlin Properties Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of val and var property modification
What is the output of this Kotlin code?
Kotlin
class Person { val name = "Alice" var age = 30 } fun main() { val p = Person() // p.name = "Bob" // Uncommenting this line causes error p.age = 31 println("Name: ${p.name}, Age: ${p.age}") }
Attempts:
2 left
💡 Hint
Remember val means read-only property, var means mutable property.
✗ Incorrect
The val property 'name' cannot be reassigned, so the commented line would cause a compilation error if uncommented. The var property 'age' can be changed, so age becomes 31.
❓ Predict Output
intermediate2:00remaining
Property mutability in data classes
What will be the output of this Kotlin code?
Kotlin
data class Point(val x: Int, var y: Int) fun main() { val p = Point(10, 20) // p.x = 15 // Uncommenting causes error p.y = 25 println("x = ${p.x}, y = ${p.y}") }
Attempts:
2 left
💡 Hint
val properties cannot be reassigned, var properties can.
✗ Incorrect
The val property 'x' is immutable and cannot be changed after initialization. The var property 'y' can be changed, so it becomes 25.
🔧 Debug
advanced2:00remaining
Identify the error with val property reassignment
What error does this Kotlin code produce?
Kotlin
class Car { val model = "Sedan" } fun main() { val c = Car() c.model = "SUV" println(c.model) }
Attempts:
2 left
💡 Hint
val properties cannot be reassigned after initialization.
✗ Incorrect
The property 'model' is declared with val, so it cannot be reassigned. Trying to assign a new value causes a compilation error.
🧠 Conceptual
advanced2:00remaining
Difference between val and var in Kotlin properties
Which statement correctly describes the difference between val and var properties in Kotlin?
Attempts:
2 left
💡 Hint
Think about whether you can change the value after it is set.
✗ Incorrect
val means the property is read-only after initialization, var means it can be changed anytime.
❓ Predict Output
expert3:00remaining
Output with val and var in inheritance
What is the output of this Kotlin code?
Kotlin
open class Animal { open val sound: String = "" } class Dog : Animal() { override val sound = "Bark" } class Cat : Animal() { override var sound = "Meow" } fun main() { val dog = Dog() val cat = Cat() println("Dog sound: ${dog.sound}") println("Cat sound: ${cat.sound}") cat.sound = "Purr" println("Cat new sound: ${cat.sound}") }
Attempts:
2 left
💡 Hint
val can be overridden by val, var can be overridden by var, but val cannot be overridden by var and vice versa.
✗ Incorrect
Dog overrides val with val, which is allowed. Cat attempts to override the open val 'sound' with var, which is not allowed in Kotlin because it violates the immutability contract of the base class property. This causes a compilation error.