What is the equivalent of Java static methods in Kotlin?
What is the equivalent of Java static methods in Kotlin?
In Kotlin, there are a few ways to achieve the functionality of Java static methods:
class CompanyUtils {
companion object {
fun getCompanyAddress(): String {
return "MindOrks, G-773, GROUND FLOOR SUNCITY, SECTOR-54 GURUGRAM, HR"
}
}
}
val companyAddress = CompanyUtils.getCompanyAddress()
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.
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
Chưa có bình luận nào