kotlin中类中的对象和伴生对象之间有什么区别?

Example:

class MyClass {

    object Holder {
        //something
    }

    companion object {
        //something
    }
}

I already read that companion object shall be used, if the containing parameters/methods are closely related to its class.

But why is there also the possibility of declaring a normal object in the class? Because it behaves exactly like the companion, but it must have a name.

它的"静电"(我来自java端)的生命周期有没有什么不同?

推荐答案

Objects can implement interfaces. Inside a class, defining a simple object that doesn't implement any interfaces has no benefit in most cases. However, defining multiple objects that implement various interfaces (e.g. Comparator) can be very useful.

就生命周期而言,在类中声明的伴随对象和命名对象没有区别.

Kotlin相关问答推荐

在Kotlin中处理结果的高阶函数

在 Kotlin 中定义基于多态函数的泛型函数

在 Kotlin 中实现并输入 Either

Mockk:对同一函数进行两次存根会忽略第一个行为

为什么Kotlin有次构造函数和init块?

在协程上下文中重新抛出异常

Flow.state In() 未从其来源接收新值

Kotlin 函数有 2 个参数用于对 Map 或 List 进行排序

如何通过 compose 处理剪切区域?

在 kotlin 中模拟伴随对象函数

Kotlin:内部类如何访问在外部类中声明为参数的变量?

如何解决此错误请Kotlin:[Internal Error] java.lang.ExceptionInInitializerError

Hilt Activity 必须附加到 @AndroidEntryPoint 应用程序

验证和 DDD - kotlin 数据类

更新到版本4.10.1/4.10.2后 Gradle 同步失败

使用导航组件在BottomNavigationView中传递参数

kotlin中密封类和密封接口的区别是什么

Kotlin - 如果不为空,则使用修改后的 Obj props 覆盖 Obj props

如何在不绑定ViewModel(MVVM)中的UI的情况下使用android导航?

Kotlin 中的填充字符串