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

middle

What are coroutines in Kotlin?

middle

What is the equivalent of Java static methods 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