17

I've created a Kotlin subclass of a Java class:

class AlarmReceiver : WakefulBroadcastReceiver() {

    companion object {
        const val ACTION_NOTIFY = "..."
    }

    override fun onReceive(context: Context, intent: Intent) { ... }
}

WakefulBroadcastReceiver has two static methods:

  • static boolean completeWakefulIntent(Intent intent)
  • static ComponentName startWakefulService(Context context, Intent intent)

and calling these from within my AlarmReceiver class works just as I expect. However, I'd like to call one of these methods outside of my Kotlin subclass.

The Problem

If I try AlarmReceiver.completeWakefulIntent(intent) from a different Kotlin class, I get the following compilation error:

Unresolved reference: completeWakefulIntent

I think this is because the compiler is trying to resolve the method on AlarmReceiver's companion object instead of finding the inherited method from its superclass. As a workaround, I can directly define a method with the same signature on AlarmReceiver.Companion:

class AlarmReceiver : WakefulBroadcastReceiver() {

    companion object {
        const val ACTION_NOTIFY = "..."

        // Just call the superclass implementation for now
        fun completeWakefulIntent(intent: Intent): Boolean =
            WakefulBroadcastReceiver.completeWakefulIntent(intent)
    }

    ...
}

I think this has the same behavior I would have gotten had I relied on the default inherited method from a Java subclass, but I'm wondering if there's a better way to do this.

Is there a way to call an inherited static Java method on a Kotlin subclass?

Ronald Martin
  • 4,278
  • 3
  • 27
  • 32

1 Answers1

18

In Kotlin, unlike Java, static members are not inherited by subclasses, even though they can be called inside a subclass without the base class name.

Outside a subclass, you have to call the base class static functions using the base class name:

WakefulBroadcastReceiver.completeWakefulIntent(intent)

This behavior seems to lie within the companion objects concept: companion objects of classes in a hierarchy are not included into each other.

Interestingly, for interfaces the situation is a bit different: interface static members cannot be referenced in subclasses without the interface name. This behavior is the same to that in Java.

Community
  • 1
  • 1
hotkey
  • 140,743
  • 39
  • 371
  • 326
  • Ah, that would explain it. Do you happen to know where it's documented that static members are not inherited? – Ronald Martin Aug 26 '16 at 17:53
  • 1
    Nope, I haven't come across any mention of it in the docs. The most *official* explanation seems to be [this one](https://www.reddit.com/r/Kotlin/comments/3oj1xm/how_to_refer_to_super_static_fields_in_kotlin_code/cvxxtan?st=isc2avuz&sh=0f63921a) given by @yole. – hotkey Aug 26 '16 at 18:00
  • Thanks! I also didn't see anything in the docs and probably wouldn't have found this on my own. – Ronald Martin Aug 26 '16 at 18:08