There is no static
keyword in Kotlin.
What is the best way to represent a static
Java method in Kotlin?
In Java, we can write in below way
class MyClass {
public static int myMethod() {
return 1;
}
}
In Kotlin, we can write in below way
class MyClass {
companion object {
fun myMethod() : Int = 1
}
}
a companion is used as static in Kotlin.
Kotlin has no any static keyword. You used that for java
class AppHelper {
public static int getAge() {
return 30;
}
}
and For Kotlin
class AppHelper {
companion object {
fun getAge() : Int = 30
}
}
Call for Java
AppHelper.getAge();
Call for Kotlin
AppHelper.Companion.getAge();
I think its working perfectly.
You can achieve the static functionality in Kotlin by Companion Objects
A companion object cannot be declared outside the class.
class MyClass{
companion object {
val staticField = "This is an example of static field Object Decleration"
fun getStaticFunction(): String {
return "This is example of static function for Object Decleration"
}
}
}
Members of the companion object can be called by using simply the class name as the qualifier:
Output:
MyClass.staticField // This is an example of static field Object Decleration
MyClass.getStaticFunction() : // This is an example of static function for Object Decleration
All static member and function should be inside companion block
companion object {
@JvmStatic
fun main(args: Array<String>) {
}
fun staticMethod() {
}
}