gpt4 book ai didi

kotlin - 为什么我们使用 "companion object"作为 Kotlin 中 Java 静态字段的一种替代品?

转载 作者:行者123 更新时间:2023-12-04 19:46:22 25 4
gpt4 key购买 nike

“伴随对象”的预期含义是什么?到目前为止,我一直在使用它来在需要时替换 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/40067602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com