Consider the following Kotlin data class and code snippet. What will be printed?
data class Person(val name: String, val age: Int) fun main() { val original = Person("Alice", 30) val copy = original.copy(age = 35) println(copy) }
Remember that copy() creates a new object with the same properties unless you override them.
The copy() function creates a new Person object with the same name but the age is overridden to 35. So the output shows Person(name=Alice, age=35).
Given the Kotlin data class and code below, what will be printed?
data class Point(val x: Int, val y: Int) fun main() { val point = Point(10, 20) val (a, b) = point println("a = $a, b = $b") }
Destructuring extracts properties in the order they are declared in the data class.
The destructuring declaration val (a, b) = point assigns a to x (10) and b to y (20).
Examine the Kotlin code below. What error will it produce when run?
data class User(val username: String, val email: String) fun main() { val user = User("bob", "bob@example.com") val newUser = user.copy(username = null) println(newUser) }
Check the type of the username property and what null means in Kotlin.
The username property is non-nullable String. Passing null to it causes a compile-time type mismatch error.
Consider this Kotlin data class and code. What will be printed?
data class Rectangle(val width: Int = 5, val height: Int = 10) fun main() { val rect = Rectangle(height = 20) val (w, h) = rect println("Width: $w, Height: $h") }
Default values are used when arguments are not provided during object creation.
The width uses the default value 5, while height is set to 20 explicitly. Destructuring assigns these values accordingly.
Given the Kotlin code below, how many entries does the resultMap contain?
data class Employee(val id: Int, val name: String, val department: String) fun main() { val emp1 = Employee(1, "John", "Sales") val emp2 = emp1.copy(name = "Jane") val (id, name, dept) = emp2 val resultMap = mapOf("id" to id, "name" to name, "department" to dept) println(resultMap.size) }
Count the number of key-value pairs added to the map.
The map contains three entries: "id", "name", and "department". So the size is 3.