Consider the following Kotlin code snippet. What will be printed?
fun main() { var number = 10 number = 20 println(number) }
Remember that var allows the variable to be changed.
The variable number is declared with var, so it can be reassigned. Initially it is 10, then changed to 20, so println outputs 20.
What will happen when running this Kotlin code?
fun main() { val text = "Hello" text = "World" println(text) }
val means the variable cannot be reassigned.
The variable text is declared with val, which means it is read-only. Trying to assign a new value causes a compilation error.
Analyze this Kotlin code and determine the output.
fun main() { var list = mutableListOf(1, 2, 3) list.add(4) println(list) }
Mutable lists can be changed even if declared with var.
The variable list is mutable and declared with var. Adding 4 modifies the list, so printing it shows all four elements.
What will happen when running this Kotlin code?
fun main() { val list = mutableListOf(1, 2, 3) list = mutableListOf(4, 5, 6) println(list) }
val means the reference cannot be changed, even if the object is mutable.
The variable list is declared with val, so you cannot assign a new list to it. This causes a compilation error.
Which statement best explains why var is used for mutable references in Kotlin?
Think about what var allows you to do with a variable.
var means the variable's reference can be changed to point to a different object or value. It does not make the object immutable or handle synchronization.