Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using
fun instead of constructor.Using
var or init in the constructor declaration.✗ Incorrect
In Kotlin, the primary constructor is declared right after the class name using the
constructor keyword or directly with parameters. Here, constructor keyword is used explicitly.2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to use
this without a property name.Using
name instead of age.✗ Incorrect
Inside the
init block, you can access the primary constructor parameters directly by their names. Here, age is printed.3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using curly braces or square brackets instead of parentheses.
Forgetting the opening parenthesis.
✗ Incorrect
The primary constructor parameters must be enclosed in parentheses after the class name.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong default value syntax.
Printing
model instead of color.✗ Incorrect
The property
color is given a default value "red". Inside the init block, the property color is printed.5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting the
constructor keyword.Using
init instead of greeting in the print statement.✗ Incorrect
The primary constructor is declared with
constructor. The property greeting uses the name parameter. The init block prints the greeting property.