Kotlin - accessing companion object members in derived types [duplicate]

淺唱寂寞╮ 提交于 2019-12-24 12:20:00

问题


Given the following code:

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

class Bar : Foo() {
    companion object {
        fun baz() { 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?


回答1:


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

The call to fez() is compiled to :

Foo.Companion.fez();

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

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



来源:https://stackoverflow.com/questions/47296133/kotlin-accessing-companion-object-members-in-derived-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!