kotlin - 为什么我们使用 "companion object"作为 Kotlin 中 Jav

“伴侣对象”的本意是什么?到目前为止,我一直在使用它来在需要时替换 Java 的 static

我很困惑:

  • 为什么叫“伴”?
  • 是否意味着要创建多个 static 属性,我必须在 companion object block 中将其组合在一起?
  • 为了立即创建一个作用域为类的单例实例,我经常这样写

:

companion object {
    val singleton by lazy { ... }
}

这似乎是一种单调的做法。有什么更好的方法?

最佳答案

  • What is the intended meaning of "companion object"? Why is it called "companion"?

    首先,Kotlin 不使用 static 成员的 Java 概念,因为 Kotlin 有自己的 concept of objects用于描述与单例状态相关的属性和函数,而 Java 类的 static 部分可以优雅地表示为单例:它是一个可以通过类名调用的单例对象。因此命名:它是一个带有类的对象。

    它的名字曾经是class object and default object , 但后来 it got renamed to companion object更清晰,也符合Scala companion objects .

    除了命名之外,它比Java的static成员更强大:它可以扩展类和接口(interface),你可以像其他对象一样引用和传递它。

  • Does it mean that to create multiple static properties, I have to group it together inside companion object block?

    是的,这是惯用的方式。或者您甚至可以按照它们的含义将它们分组到非伴随对象中:

    class MyClass {
        object IO {
            fun makeSomethingWithIO() { /* ... */ }
        }
    
        object Factory {
            fun createSomething() { /* ... */ }
        }
    }
    
  • To instantly create a singleton instance that is scoped to a class, I often write /*...*/ which seems like an unidiomatic way of doing it. What's the better way?

    这取决于您在每种特定情况下的需要。您的代码非常适合存储绑定(bind)到在第一次调用时初始化的类的状态。

    如果你不需要它与一个类连接,只需使用对象声明:

    object Foo {
        val something by lazy { ... }
    }
    

    您也可以删除 lazy { ... } delegation使属性在第一类使用时初始化,就像 Java 静态初始化器一样

    您还可以找到initializing singleton state 的有用方法.

关于kotlin - 为什么我们使用 "companion object"作为 Kotlin 中 Java 静态字段的一种替代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38381748/

相关文章:

random - 如何在 Kotlin 中获取随机数?

hibernate - 带有 JPA : default constructor hell 的 Ko

asynchronous - Kotlin协程中的launch/join和async/await有什

kotlin - 什么是 Kotlin 双键 (!!) 运算符?

dictionary - 如何在 Kotlin 中将列表转换为 map ?

inheritance - 在 Kotlin 中扩展数据类

java - Java 的 String[] 的 Kotlin 等价物是什么?

kotlin - 如何在 Kotlin 中将 String 转换为 Long?

design-patterns - 如何在 Kotlin 中实现 Builder 模式?

kotlin - 在 Kotlin 中试用资源