Challenge - 5 Problems
Primary Constructor and Init Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of init block with primary constructor
What is the output of this Kotlin code?
Kotlin
class Person(val name: String) { init { println("Hello, $name") } } fun main() { val p = Person("Anna") }
Attempts:
2 left
💡 Hint
The init block runs right after the primary constructor.
✗ Incorrect
The init block runs immediately after the primary constructor. It prints "Hello, Anna" because the name property is initialized with "Anna".
❓ Predict Output
intermediate2:00remaining
Value of property after init block
What is the value of 'age' after creating the object?
Kotlin
class User(val name: String, val birthYear: Int) { val age: Int init { age = 2024 - birthYear } } fun main() { val u = User("Tom", 1990) println(u.age) }
Attempts:
2 left
💡 Hint
Age is calculated in the init block using birthYear.
✗ Incorrect
The init block calculates age as 2024 - 1990 = 34, so u.age is 34.
❓ Predict Output
advanced2:00remaining
Multiple init blocks execution order
What is the output of this Kotlin code?
Kotlin
class Box(val width: Int) { init { println("First init: width = $width") } init { println("Second init: width * 2 = ${width * 2}") } } fun main() { val b = Box(5) }
Attempts:
2 left
💡 Hint
Init blocks run in the order they appear in the class.
✗ Incorrect
Init blocks run top to bottom. First prints width, then prints width * 2.
❓ Predict Output
advanced2:00remaining
Property initialization with primary constructor and init
What is the output of this Kotlin program?
Kotlin
class Rectangle(val height: Int, val width: Int) { val area: Int init { area = height * width } } fun main() { val r = Rectangle(3, 4) println(r.area) }
Attempts:
2 left
💡 Hint
Area is calculated in the init block from height and width.
✗ Incorrect
The init block sets area to 3 * 4 = 12, so printing r.area outputs 12.
❓ Predict Output
expert2:00remaining
Effect of property shadowing in init block
What is the output of this Kotlin code?
Kotlin
class Sample(x: Int) { val x: Int = x + 1 init { println(this.x) } } fun main() { val s = Sample(5) }
Attempts:
2 left
💡 Hint
Class property shadows constructor parameter; init uses property.
✗ Incorrect
The property 'x' is initialized to 5 + 1 = 6. The init block prints the property value 6.