0
0
Kotlinprogramming~10 mins

Secondary constructors 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 define a secondary constructor in the class.

Kotlin
class Person {
    var name: String
    constructor(name: String) {
        this.name = [1]
    }
}
Drag options to blanks, or click blank then click option'
Aname
BPerson
Cthis.name
Dconstructor
Attempts:
3 left
💡 Hint
Common Mistakes
Using this.name on the right side instead of the parameter.
Forgetting to assign the parameter to the property.
2fill in blank
medium

Complete the code to call the primary constructor from the secondary constructor.

Kotlin
class Person(val name: String) {
    constructor() : this([1]) {
        println("Secondary constructor called")
    }
}
Drag options to blanks, or click blank then click option'
APerson
B"Unknown"
Cthis.name
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to use name without defining it.
Using this.name which is not valid here.
3fill in blank
hard

Fix the error in the secondary constructor call to the primary constructor.

Kotlin
class Person(val name: String) {
    constructor(age: Int) : this([1]) {
        println("Age is $age")
    }
}
Drag options to blanks, or click blank then click option'
A"Unknown"
B"age"
Cage
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Passing age directly which is an Int.
Passing "age" as a string literal which is not meaningful here.
4fill in blank
hard

Fill both blanks to create a secondary constructor that calls the primary constructor with a default name and prints a message.

Kotlin
class Person(val name: String) {
    constructor() : this([1]) {
        println([2])
    }
}
Drag options to blanks, or click blank then click option'
A"Guest"
B"Secondary constructor called"
C"Hello"
D"Name not provided"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-string value in the first blank.
Printing the wrong message.
5fill in blank
hard

Fill all three blanks to define a class with a primary constructor and two secondary constructors calling it with different default names.

Kotlin
class Person(val name: String) {
    constructor() : this([1]) {
        println([2])
    }
    constructor(age: Int) : this([3]) {
        println("Age is $age")
    }
}
Drag options to blanks, or click blank then click option'
A"Anonymous"
B"No name provided"
C"Unknown"
D"Default"
Attempts:
3 left
💡 Hint
Common Mistakes
Using the same string for both secondary constructors.
Printing a message that doesn't match the constructor.