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

Why do we use companion object as a kind of ...

Câu trả lời

In Kotlin, the companion object is used as a replacement for Java's static fields and methods. Here are a few reasons why we use companion object in Kotlin:

Accessing Members Without an Instance

In Java, you can access static fields and methods directly using the class name, without creating an instance of the class. For example:

java Copy
Math.PI
Math.max(a, b)

In Kotlin, you can achieve similar functionality using the companion object. Any members defined inside the companion object can be accessed directly using the class name, just like Java's static members.

kotlin Copy
val pi = Math.PI
val max = Math.max(a, b)

Providing Utility Methods and Constants

companion object is often used to group utility methods and constants related to a class. This makes the code more organized and easier to maintain.

kotlin Copy
class Math {
    companion object {
        const val PI = 3.14159
        fun max(a: Int, b: Int): Int {
            return if (a > b) a else b
        }
    }
}

Implementing Singleton Pattern

In Kotlin, you can use companion object to implement the Singleton ...

expert

expert

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

middle

How would you create a singleton with parameter in Kotlin?

junior

What is a primary constructor in Kotlin?

expert

What is the difference between Java field and Kotlin property?

Bình luận

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

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