What is the equivalent of Java static methods in Kotlin?

前端 未结 28 1190
眼角桃花
眼角桃花 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 09:53

    Write them directly to files.

    In Java (ugly):

    package xxx;
    class XxxUtils {
      public static final Yyy xxx(Xxx xxx) { return xxx.xxx(); }
    }
    

    In Kotlin:

    @file:JvmName("XxxUtils")
    package xxx
    fun xxx(xxx: Xxx): Yyy = xxx.xxx()
    

    Those two pieces of codes are equaled after compilation (even the compiled file name, the file:JvmName is used to control the compiled file name, which should be put just before the package name declaration).

提交回复
热议问题