What is the difference between var and val in Kotlin?
What is the difference between var and val in Kotlin?
The main difference between var
and val
in Kotlin is that var
declares a mutable variable whose value can be changed, while val
declares an immutable variable whose value cannot be changed after it is assigned[1][2][4].
Some key points:
var
variables can be reassigned to a new value at any point in the code[1][2]. For example:var x = 5
x = 10 // OK
val
variables are read-only and cannot be reassigned[1][2][4]. Attempting to reassign a val
will result in a compile error. For example:val y = 5
y = 10 // Error: Val cannot be reassigned
val
can still be changed[1][2]. For example:val book = Book("Java", 1000)
book.name = "Kotlin" // OK, property can be changed
val
is similar to the final
keyword in Java, making the variable immutable[4].
var
is useful when you need to...
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào