在Kotlin中命名同伴对象有什么意义 [英] What is the point of naming a companion object in kotlin

查看:182
本文介绍了在Kotlin中命名同伴对象有什么意义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伴侣对象的文档具有以下示例

class MyClass {
    companion object Factory {
        fun create(): MyClass = MyClass()
    }
}

此处Factory是伴随对象的名称.然后继续说:

Here Factory is the name of the companion object. It then goes on to say:

陪伴对象的名称可以省略,在这种情况下,将使用名称Companion:

但是,我没有看到使用随播对象名称的示例.

However there is no example that I can see that uses the name of the companion object.

由于每个类只能有一个伴随对象(否则会出现Only one companion object is allowed per class错误),所以这个名称对我来说就像是一些毫无用处的语法糖.

Since you can only have one companion object per class (otherwise you get a Only one companion object is allowed per class error) the name feels like some pretty useless syntactic sugar to me.

伴随对象的名称实际上可以用来做什么? 为什么要麻烦使用任何名称呢?

What can the name of the companion object actually be used for? Why would one bother to use any name for it?

推荐答案

您可以使用随播广告的名称,例如:

You can use the name of the companion like:

MyClass.create()           // not via companion name
MyClass.Companion.create() // via default companion name
MyClass.Factory.create()   // via companion name

对于Kotlin来说,名称可能并不那么重要,因为您可以在不知道存在伴随对象的情况下直接访问该方法(上面的第一行).如果您想更明确地访问此类功能,则更像是个人风格.

The name is maybe not that important for Kotlin, because you can just access the method without knowing that there is a companion object (line one above). It is more like a personal style, if you want to make the access to such functions more explicit.

但是对于 java interop 却有所不同,因为您必须通过伴随名称来访问该函数:

But for java interop it makes a difference, because you have to access the function via the companion name:

    MyClass.Factory.create();   // with named companion
    MyClass.Companion.create(); // with unnamed comanion

这篇关于在Kotlin中命名同伴对象有什么意义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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