Search code examples
kotlinstatic-methods

How to call parent static method using child class in kotlin?


I have a java class AAA with a static method:

public class AAA {
    public static void foo() {}
}

and a kotlin class which extends it:

class BBB : AAA() {}

Now in other kotlin file I would like to call that method. If I do it like this then it works:

fun bar() {
    AAA.foo()
}

but when I'm doing it like this it doesn't compile (Unresolved reference: foo):

fun bar() {
    BBB.foo()
}

Is it possible to call parent static method using child class BBB in kotlin? In java there is no problem with that.


Solution

  • No, according to Calling Java from Kotlin, this is how Java's static members are ported to Kotlin:

    Static members of Java classes form "companion objects" for these classes. You can't pass such a "companion object" around as a value but can access the members explicitly.

    You don't inherit the companion object of a superclass in Kotlin.

    open class A {
        companion object {
            fun foo() {}
        }
    }
    
    class B: A() {
        fun bar() {
            // this doesn't work because B.Companion does not exist
            B.foo()
    
            // these work, because these are implicitly A.Companion.foo()
            foo()
            A.foo()
        }
    }
    

    Technically, you could write a companion object in BBB that has all the static members of AAA:

    class BBB : AAA() {
        companion object {
            // this allows you to do BBB.foo()
            val foo = AAA::foo
        }
    }
    

    Though I think that's beside the point.

    That said, this doesn't really matter at the end of the day. Practically, you don't lose anything by doing AAA.foo().