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

What is a purpose of Companion Objects in Kotlin?

Câu trả lời

The purpose of companion objects in Kotlin is to provide a way to define class-level variables and methods, similar to static members in Java and other languages[1][2]. Companion objects allow you to access data and behavior that is tied to a class itself, rather than instances of the class[4].

Some key points about companion objects:

  • They are declared using the companion keyword inside a class[1][2]
  • Variables and functions defined in a companion object can be accessed using the class name, without needing to create an instance of the class[1][2][4]
  • Companion objects are initialized when the class is loaded, similar to static initializers[1]
  • They can access private members of the enclosing class[2]
  • Companion objects are not the same as singletons in Kotlin. Singletons are created using the object keyword[1].

Companion objects are useful for:

  • Defining constants or configuration value...
middle

middle

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

expert

What is a motivation to make classes final by default in Kotlin? Do you agree with that decision?

middle

When would you use Elvis operator in Kotlin?

middle

What are some disadvantages of Kotlin?

Bình luận

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

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