Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call a parent method from a companion object in kotlin

Tags:

kotlin

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?

like image 727
DanielD Avatar asked Nov 08 '25 09:11

DanielD


1 Answers

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.

like image 93
fweigl Avatar answered Nov 12 '25 17:11

fweigl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!