Kotlin:类中的对象和伴侣对象之间的区别 [英] Kotlin: Difference between object and companion object in a class

查看:103
本文介绍了Kotlin:类中的对象和伴侣对象之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the difference between an object and a companion object in a class in kotlin?

示例:

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方面)生命周期是否可能有所不同?

Is there maybe a difference in its "static" (I'm from the java side) lifecycle?

推荐答案

对象可以实现接口.在类内部,定义一个不实现任何接口的简单对象在大多数情况下没有好处.但是,定义实现各种接口(例如Comparator)的多个对象可能非常有用.

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.

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

In terms of lifecycle, there is no difference between a companion object and a named object declared in a class.

这篇关于Kotlin:类中的对象和伴侣对象之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆