伴侣对象相对于普通对象有什么好处?

时间:2017-11-01 00:26:32

标签: kotlin

像这样的Kotlin代码:

select interaction_id,concat_ws(':--  ',party,phrase) as final,start_offset,end_offset  
from aads_piim.A608232_Myvoice_wt_transcript 
order by interaction_id,start_offset,end_offset

可以简单地改为

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

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

1 个答案:

答案 0 :(得分:3)

其中一个关键差异是成员的可见度。 在伴随对象中,对包含类的可见性是 - 如果成员是类的一部分 - 原始对象不是这种情况。

下面的示例显示您无法使用“对象”来实现类的私有静态内部。

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);
}