What is the equivalent of Java static methods in Kotlin?

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

    For Android using a string from a single activity to all the necessary activity. Just like static in java

    public final static String TEA_NAME = "TEA_NAME";

    Equivalent approach in Kotlin:

    class MainActivity : AppCompatActivity() {
        companion object {
            const val TEA_NAME = "TEA_NAME"
        }
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
        }
    }
    

    Another activity where value is needed:

    val teaName = MainActivity.TEA_NAME
    

提交回复
热议问题