What is the equivalent of Java static methods in Kotlin?

0 votes
asked Feb 5 by Hitesh Garg (355 points)  

Since there is no static keyword in Kotlin.
How do I write static variables and methods in Kotlin?

1 Answer

0 votes
answered Feb 7 by Hitesh Garg (355 points)  

"companion object" is the alternative for static fields and methods in Java.

So the java code like this:

class Foo {
  public static String a() { return "hello"; }

In kotlin will look like

class Foo {
  companion object {
     fun a() : String = "hello"

You can then use it from inside Kotlin code as

Welcome to Codingeek Q&A, where you can ask questions and receive answers from other members of the community.