0
0
Kotlinprogramming~10 mins

Data classes for value holders 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 data class named Person with two properties: name and age.

Kotlin
data class Person([1] name: String, val age: Int)
Drag options to blanks, or click blank then click option'
Aval
Bvar
Cfun
Dclass
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'var' instead of 'val' for properties in data classes.
Trying to use 'fun' or 'class' inside the parameter list.
2fill in blank
medium

Complete the code to create an instance of the Person data class with name "Alice" and age 30.

Kotlin
val person = Person([1] = "Alice", age = 30)
Drag options to blanks, or click blank then click option'
Aname
BPerson
Cage
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'age' instead of 'name' for the first argument.
Trying to use 'val' or 'Person' as argument names.
3fill in blank
hard

Fix the error in the code to correctly override the toString method in the data class.

Kotlin
data class Person(val name: String, val age: Int) {
    override fun [1](): String {
        return "Person(name=$name, age=$age)"
    }
}
Drag options to blanks, or click blank then click option'
AtoStr
BtoString
Cstringify
Dprint
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect method names like 'toStr' or 'stringify'.
Trying to override 'print' instead of 'toString'.
4fill in blank
hard

Fill both blanks to create a copy of a Person instance with a new age.

Kotlin
val olderPerson = person.[1]([2] = person.age + 1)
Drag options to blanks, or click blank then click option'
Acopy
Bage
Cname
Dclone
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'clone' instead of 'copy'.
Changing 'name' instead of 'age'.
5fill in blank
hard

Fill all three blanks to create a data class with default values and a method that returns a greeting.

Kotlin
data class Person(val name: String = [1], val age: Int = [2]) {
    fun greet() = "Hello, my name is $[3]"
}
Drag options to blanks, or click blank then click option'
A"Unknown"
B0
Cname
D"Guest"
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string literal instead of the property name in the greeting.
Setting default age to a string instead of a number.