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

What is the equivalent of Java static methods in Kotlin?

Câu trả lời

In Kotlin, there are a few ways to achieve the functionality of Java static methods:

  1. Using a companion object[1][2][4]: You can define static-like methods inside a companion object of a class. These methods can be called using the class name as the qualifier, e.g.:
kotlin Copy
class CompanyUtils {
    companion object {
        fun getCompanyAddress(): String {
            return "MindOrks, G-773, GROUND FLOOR SUNCITY, SECTOR-54 GURUGRAM, HR"
        }
    }
}

val companyAddress = CompanyUtils.getCompanyAddress()
  1. Using the @JvmStatic annotation[1][3][4]: You can annotate functions inside a companion object or object declaration with @JvmStatic to generate static methods in the enclosing class. This allows calling the methods directly using the class name in both Kotlin and Java.

  2. Using package-level functions[1][2]: You can define functions at the package level, outside of any class. These functions will be compiled as static methods in the corresponding Java c...

middle

middle

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

middle

What is the difference between const and val ?

middle

What is lateinit in Kotlin and when would you use it?

junior

What is the idiomatic way to remove duplicate strings from array?

Bình luận

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

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