乐闻世界logo
搜索文章和话题

What is the difference between var and val in Kotlin?

1个答案

1

In Kotlin, var and val are keywords used to declare variables, but they have a key difference:

  • var:Variables declared with var are mutable. This means the value can be changed during the variable's lifetime. For example:
kotlin
var name = "John" println(name) // Output John name = "Eric" println(name) // Output Eric
  • val:Variables declared with val are immutable, meaning once assigned, the value cannot be changed. In many aspects, val is similar to a final variable in Java. For example:
kotlin
val age = 30 println(age) // Output 30 // age = 31 // This would cause a compilation error, as variables declared with `val` cannot be reassigned

Using val instead of var can make the code safer and easier to maintain. Immutability helps avoid many errors caused by mutable state, and it is particularly beneficial for multi-threaded environments because you don't have to worry about one thread changing the variable's value affecting other threads.

For example, in an application with multiple users, you might have an object representing user information:

kotlin
val user = User("Alice", 28)

If the User class is immutable, you can ensure that no code can change the state of the user object, which helps prevent various concurrency issues and other complex errors. If you need to update user information, it is typically done by creating a new user object rather than modifying the properties of the existing object.

2024年7月26日 21:36 回复

你的答案