Why do we use companion object as a kind of ...
Why do we use companion object as a kind of ...
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:
In Java, you can access static fields and methods directly using the class name, without creating an instance of the class. For example:
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.
val pi = Math.PI
val max = Math.max(a, b)
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.
class Math {
companion object {
const val PI = 3.14159
fun max(a: Int, b: Int): Int {
return if (a > b) a else b
}
}
}
In Kotlin, you can use companion object
to implement the Singleton ...
expert
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào