Kotlin代码是这样的:
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静态函数,但使用伴侣对象还有其他优点吗?
主要区别之一是成员的可见性。在伴生对象中,对包含类的可见性就像成员是该类的一部分一样 - 对于原始对象而言,情况并非如此。
下面的示例表明您不能使用“对象”来实现类的私有静态内部。
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);
}
| 归档时间: | 
 | 
| 查看次数: | 358 次 | 
| 最近记录: |