What is the equivalent of Java static methods in Kotlin?

前端 未结 28 1130
眼角桃花
眼角桃花 2020-11-27 09:03

There is no static keyword in Kotlin.

What is the best way to represent a static Java method in Kotlin?

28条回答
  •  清酒与你
    2020-11-27 10:00

    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.

提交回复
热议问题