Câu hỏi phỏng vấn Kotlin
Câu hỏi

What is the difference between var and val in Kotlin?

Câu trả lời

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:
kotlin Copy
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:
kotlin Copy
val y = 5 
y = 10 // Error: Val cannot be reassigned
  • However, the properties of an object assigned to a val can still be changed[1][2]. For example:
kotlin Copy
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

junior

Gợi ý câu hỏi phỏng vấn

expert

What is the difference between launch/join and async/await in Kotlin coroutines?

middle

What is lateinit in Kotlin and when would you use it?

middle

What are coroutines in Kotlin?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào