kotlin 中 object,companion object,class,data class 的区别

发布时间: 2022-10-28 13:57:29 作者: 大象笔记

object

a static instance of a class that there is only one of, otherwise known as a singleton

例如:

object Tool {
    fun checksum {
        // ...
    }
}

Tool.checksum()  

companion object

companion:同伴、伴侣的意思。

例如:

class ExampleClass {
  companion object {
    // Things that would be static in Java would go here in Kotlin
    private const val str = "asdf"
    fun myStaticMethod() {
        // ...
    }
  }

  fun example() {
    // I can access private variables in my companion object
    println(str)
  }
}

// 调用
ExampleClass.myStaticMethod()

class

data class

例如:

data class PlaceholderItem(val id: String, val content: String, val details: String) {
    override fun toString(): String = content
}

参考

我是一名山东烟台的开发者,联系作者