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

val mutableList vs var immutableList . When to use which in Kotlin?

Câu trả lời

Here's an explanation of the differences between val mutableList and var immutableList in Kotlin, and when to use each:

val mutableList

  • A val mutableList is a mutable list that is declared using the val keyword.
  • It allows you to modify the contents of the list, such as adding, removing, or updating elements.
  • However, you cannot reassign the list to a different reference.

Example:

kotlin Copy
val mutableList = mutableListOf(1, 2, 3)
mutableList.add(4) // Allowed
mutableList = emptyList() // Not allowed

var immutableList

  • A var immutableList is an immutable list that is declared using the var keyword.
  • It allows you to reassign the list to a different reference.
  • However, you cannot modify the contents of the list once it is created.

Example:

kotlin Copy
var immutableList = listOf(1, 2, 3)
immutableList = emptyList() // Allowed
immutableList.add(4) // Not allowed

W...

middle

middle

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

middle

What is a difference between a class and object in Kotlin?

middle

What are coroutines in Kotlin?

middle

Explain lazy initialization in Kotlin

Bình luận

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

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