Consider the following Kotlin code snippet. What will be printed?
val x = 10 var y = 20 y = 30 println("x = $x, y = $y")
Remember that val means immutable and var means mutable.
val x = 10 creates an immutable variable, so x cannot change. var y = 20 creates a mutable variable, so y can be reassigned to 30. The print statement shows the current values.
Which of the following is the best reason why Kotlin uses immutability by default with val?
Think about how bugs happen when data changes unexpectedly.
Immutability prevents accidental changes, which reduces bugs and makes reasoning about code easier. It does not force all variables to be constants, only those declared with val. Mutable variables can still be declared with var.
Examine this Kotlin code snippet. What error will it cause?
val list = mutableListOf(1, 2, 3) list = mutableListOf(4, 5, 6)
Look at the val keyword and what it means for reassignment.
val means the variable reference cannot be changed. Trying to assign a new list to list causes a compilation error: 'Val cannot be reassigned'. The contents of the list can be changed, but the reference cannot.
What will this Kotlin code print?
val numbers = mutableListOf(1, 2, 3) numbers.add(4) println(numbers)
Think about what val protects: the reference or the object?
val means the reference numbers cannot point to a different list, but the list itself can be changed because it is mutable. So adding 4 works and prints the updated list.
In concurrent programming, why is immutability by default important in Kotlin?
Think about what causes bugs when many threads change the same data.
Immutable data cannot be changed after creation, so multiple threads can safely read it without causing conflicts or race conditions. Mutable data requires careful synchronization to avoid bugs.