本文介绍了Kotlin-以派生类型访问伴侣对象成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

open class Foo {
    companion object {
        fun fez() {}
    }
}

class Bar : Foo() {
    companion object {
        fun baz() { fez() }
    }
}

  • baz()可以呼叫fez()
  • 我可以打电话给Foo.fez()
  • 我可以打电话给Bar.baz()
  • 但是,我无法拨打Bar.fez()
    • baz() can call fez()
    • I can call Foo.fez()
    • I can call Bar.baz()
    • But, I cannot call Bar.fez()
    • 我如何实现最终的行为?

      How do I achieve the final behaviour?

      推荐答案

      伴随对象是其周围类的静态成员:

      A companion object is a static member of its surrounding class:

      public class Foo {
         public static final Foo.Companion Companion;
      
         public static final class Companion {
            public final void fez() {
            }
      
           //constructors
         }
      }
      

      fez()的调用被编译为:

      Foo.Companion.fez();
      

      仅供参考:所示的Java代码显示了Kotlin生成的字节码的表示形式.

      FYI: The shown Java code shows a representation of the bytecode generated by Kotlin.

      结果,您无法调用Bar.fez(),因为Bar中的Companion对象没有该方法.

      As a result, you cannot call Bar.fez() because the Companion object in Bar does not have that method.

      这篇关于Kotlin-以派生类型访问伴侣对象成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 15:03