0
0
Kotlinprogramming~10 mins

Primary constructor and init blocks 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 primary constructor with a parameter name.

Kotlin
class Person [1](val name: String) {}
Drag options to blanks, or click blank then click option'
Avar
Bfun
Cconstructor
Dinit
Attempts:
3 left
💡 Hint
Common Mistakes
Using fun instead of constructor.
Using var or init in the constructor declaration.
2fill in blank
medium

Complete the code to initialize the age property inside the init block.

Kotlin
class Person(val name: String, val age: Int) {
    init {
        println("Age is [1]")
    }
}
Drag options to blanks, or click blank then click option'
Aage
Bname
Cthis
Dconstructor
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to use this without a property name.
Using name instead of age.
3fill in blank
hard

Fix the error in the primary constructor declaration by filling the blank.

Kotlin
class Car [1] val model: String, val year: Int) {}
Drag options to blanks, or click blank then click option'
A[
B{
C<
D(
Attempts:
3 left
💡 Hint
Common Mistakes
Using curly braces or square brackets instead of parentheses.
Forgetting the opening parenthesis.
4fill in blank
hard

Fill both blanks to create a property color with a default value and print it in the init block.

Kotlin
class Bike(val model: String, val year: Int, val color: String = [1]) {
    init {
        println("Bike color is [2]")
    }
}
Drag options to blanks, or click blank then click option'
A"red"
Bcolor
Cmodel
D"blue"
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong default value syntax.
Printing model instead of color.
5fill in blank
hard

Fill all three blanks to create a class with a primary constructor, an init block that prints a greeting, and a property greeting initialized from the constructor.

Kotlin
class Greeter [1](val name: String) {
    val greeting = "Hello, [2]!"
    init {
        println([3])
    }
}
Drag options to blanks, or click blank then click option'
Aconstructor
Bname
Cgreeting
Dinit
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the constructor keyword.
Using init instead of greeting in the print statement.