我创建了一个Java类的Kotlin子类:

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)

在我的AlarmReceiver个班级里打电话给他们,效果和我预期的一样.然而,我想将其中一种方法称为outside of my Kotlin subclass.

The Problem

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

未解析的引用: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.

有没有办法在Kotlin子类上调用继承的静电Java方法?

推荐答案

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.

在子类外部,您必须使用基类名称调用基类静电函数:

WakefulBroadcastReceiver.completeWakefulIntent(intent)

这种行为似乎属于伴生对象的概念:层次 struct 中类的伴生对象彼此不包含.

有趣的是,对于接口来说情况有点不同:interface static members cannot be referenced in subclasses without the interface name.这种行为是the same to that in Java

Kotlin相关问答推荐

如何将时间值格式化为00:00和00:00:00 Kotlin?""""

如何在Jetpack Compose中从领域查询中读取数据?

如何在 Kotlin 中初始化 Short 数组?

将 java Optional 转换为 Kotlin Arrow Option

Kotlin 函数中接收者和参数的类型相同

如何使用 Firebase 和 Kotlin 在文本 (Jetpack Compose) 中显示当前用户名?

返回 kotlin 中的标签和 lambda 表达式

在 Kotlin 中,为什么在 `+` 之前但在 `.` 之前没有换行符?

如何在 Kotlin 中为变量分配另一个变量的值?

如何连接两个 kotlin 流?

如何从 kotlin 函数中 Select 正确的枚举值

无法删除部分子项.这可能是因为进程打开了文件或将其工作目录设置在目标目录中

如何创建 Kotlin DSL - DSL 语法 Kotlin

从列表中的每个对象中 Select 属性

无法解决:androidx.lifecycle:lifecycle-viewmodel-ktx:1.1.1

ActivityOptions.makeSceneTransitionAnimation 在具有多个视图的 kotlin 中不起作用

Kotlin:找不到符号类片段或其他 android 类

Kotlin 中的内联构造函数是什么?

如何解决:将Java类转换为Kotlin后出现error: cannot find symbol class ...?

查找是否在列表中找到具有特定属性值的元素