Kotlin静态方法和静态类

Kotlin静态方法和静态类

静态类

所有方法都为静态方法,如工具类、常量池、等,直接把;类名前的class替换成object

object Constants1 {
    val text = "hello world!"
}

调用

Constants1.text

静态方法

在Kotlin里静态方法可以通过“伴生对象”的方式实现,具体操作为:

在类的内部用companion object { }包裹所需的静态函数

class Constants {
    companion object {
        val text = "hello world!"
    }
}

调用

Constants.text

猜你喜欢

转载自blog.csdn.net/YULU5216/article/details/80083084