What is the equivalent of Java static methods in Kotlin?

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

    except Michael Anderson's answer, i have coding with other two way in my project.

    First:

    you can white all variable to one class. created a kotlin file named Const

    object Const {
        const val FIRST_NAME_1 = "just"
        const val LAST_NAME_1 = "YuMu"
    }
    

    You can use it in kotlin and java code

     Log.d("stackoverflow", Const.FIRST_NAME_1)
    

    Second:

    You can use Kotlin's extension function
    created a kotlin file named Ext, below code is the all code in Ext file

    package pro.just.yumu
    
    /**
     * Created by lpf on 2020-03-18.
     */
    
    const val FIRST_NAME = "just"
    const val LAST_NAME = "YuMu"
    

    You can use it in kotlin code

     Log.d("stackoverflow", FIRST_NAME)
    

    You can use it in java code

     Log.d("stackoverflow", ExtKt.FIRST_NAME);
    

提交回复
热议问题