与普通对象相比,同伴对象有什么优势? [英] What are the advantages of a companion object over a plain object?

查看:93
本文介绍了与普通对象相比,同伴对象有什么优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

科特琳代码如下:

class Foo {
  companion object {
     fun a() : Int = 1
  }
  fun b() = a() + 1
}

可以简单地更改为

object FooStatic {
   fun a() : Int = 1
}

class Foo {
  fun b() = FooStatic.a()
}

我知道可以使用伴随对象允许将其用作真正的java静态函数,但是使用伴随对象还有其他优点吗?

I'm aware that the companion object can be used to allow use as real java static function, but are there any other advantages to using the companion object?

推荐答案

关键区别之一是成员的可见性. 在同伴对象中,对于包含类的可见性就好像成员是该类的一部分一样,而对于原始对象则不是这种情况.

One of the key differences is visibility of the members. In a companion object, visibility to the containing class is as-if the members were part of the class - this is not the case for a raw object.

下面的示例显示您不能使用对象"来实现类的私有静态内部.

The example below shows that you cant use an "object" to implement private static internals of a class.

package com.example

class Boo {

    companion object Boo_Core {
        // Public "static" call that non-Boo classes should not be able to call
        fun add_pub(a:Int) = a+1;

        // Internal "static" call that non-Boo classes should not be able to call
        private fun add_priv(a:Int) = a+1;
    }

    // OK: Functions in Boo can call the public members of the companion object
    fun blah_pub(a:Int) = add_pub(a)
    // OK: Functions in Boo can call the private members of the companion object
    fun blah_priv(a:Int) = add_priv(a)
}

//Same idea as the companion object, but as an "object" instead.
object Foo_Core {
    fun add_pub(a:Int) = a+1
    private fun add_priv(a:Int) = a+1;
}

class Foo {
    // OK Foo can get Foo_Cors add_pub
    fun blah_pub(a:Int) = Foo_Core.add_pub(a);

    // ERROR: can not get to add_priv
    // fun blah_priv(a:Int) = Foo_Core.add_priv(a);
}

class AnInterloper {

    // OK Other classes can use public entries in Foo.
    fun blah_foo_pub(a:Int) = Foo_Core.add_pub(a); 

    // ERROR Other classes can use public entries in Foo.
    // fun blah_foo_priv(a:Int) = Foo_Core.add_priv(a); 

    // OK: Other classes can use public Boo classes
    fun blah_boo_pub(a:Int) = Boo.add_pub(a);

    // ERROR: Other classes can not use private Boo classes
    // fun blah_boo_priv(a:Int) = Boo.add_priv(a);
}

这篇关于与普通对象相比,同伴对象有什么优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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