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

1

2

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?

Mistrustful answered 14/11, 2017 at 22:14 Comment(0)
I
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.

Intensify answered 14/11, 2017 at 23:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.