4

I have a Super class:

open class A {
    fun doStuff() {

    }
}

and then I have a sub Class which extends that:

class B: A() {
   companion object {
        doStuff() //compile error
   }
}

How can I call my doStuff() method from the companion object?

DanielD
  • 1,315
  • 4
  • 17
  • 25
  • 1
    You also can't do this from class A's companion object. – Paul Hicks Dec 14 '17 at 00:06
  • 1
    "can't " may not be the entire story, you probably shouldn't. You could pass an instance of the parent class into a method in the companion object and then call the instance method from there, but it is awkward. Better to create an instance method and call companion object stuff from there. – Droid Teahouse Sep 13 '18 at 19:51

2 Answers2

11

You can't.

The companion object is a rough equivalent of the static keyword in Java. The doStuff() function of class A(and its subclasses) can only be called from an actual object of that class (like A().doStuff() or B().doStuff())

When trying to call that function from B's companion object, there is no such object of A (or B) on which you could call that function, since you're in a static context.

If you'd write the Java equivalent of what you posted, you'd receive the error

non-static method cannot be referenced from a static context

which is more descriptive than what you're probably getting from Kotlin's compiler and is well explained here.

fweigl
  • 21,278
  • 20
  • 114
  • 205
0

You have to make two class A1 and B1 where B1 inherits from A1 and then inherit A companion object from A1 and inherit B companion Object from B1, then you can call methods of A1 class from B companion object . Note that method of A1 class are also methods of A class.

S.Bozzoni
  • 998
  • 9
  • 18