What is the equivalent of Java static methods in Kotlin?

前端 未结 28 1193
眼角桃花
眼角桃花 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:03

    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.

提交回复
热议问题