我刚刚开始try 使用Kotlin台Android应用程序.我只想继承这样的Application类:

class SomeApp : Application {

}

But the compiler raises the warning:

enter image description here

and suggestion changes it to:

class SomeApp : Application() {
    override fun onCreate() {
        super.onCreate()
    }
}

我读了大约primary and secondary constructors in the docs本.所以,如果超类有一个主构造函数,那么有必要在这里写吗?像应用程序类一样,它有自己的构造函数

public Application() {
    super(null);
}

那么就有必要为派生的?或者我不能像Java那样做:

class SomeApp : Application {
   constructor SomeApp(){
      super();
    }
}

or this error suggests something else? Can anyone explain me in detail? I'm very new to the language and this looks weird to me.

编辑:在java中,我可以执行以下操作:class SomeApp extends Application{ }

It has implicit constructor, so I do not have to write: class SomeApp extends Application{ public Application(){ super(); } } But in kotlin do I have to define empty constructor like the following: class SomeApp:Application(){ } ?

推荐答案

This is not about primary/secondary constructors.

在JVM(以及几乎任何其他地方)上,当您创建SomeApp的实例时会调用基类Application的构造函数

In Java the syntax is like you said:

class SomeApp : Application {
    constructor SomeApp(){
      super();
    }
}

这里你must声明一个constructor,然后你must调用一个超类的构造函数.

在Kotlin中,概念相同,但语法更好:

class SomeApp() : Application() {
    ...
}

在这里,您声明了一个没有参数的构造函数SomeApp(),并说它调用了Application(),在这种情况下没有参数.这里Application()的效果与java代码片段中的super()完全相同.

在某些情况下,可以省略一些括号:

class SomeApp : Application()

The text of the error says: This type has a constructor, and thus must be initialized here. That means that type Application is a class, not an interface. Interfaces don't have constructors, so the syntax for them does not include a constructor invocation (brackets): class A : CharSequence {...}. But Application is a class, so you invoke a constructor (any, if there are several), or "initialize it here".

Kotlin相关问答推荐

如何在使用Kotlin Coroutines时检测和记录何时出现背压

我可以检测一个函数是否在Kotlin中被递归调用(即,重入)吗?

从 Kotlin 的父类获取函数注解

在 Kotlin 中,为什么我们要在闭包中捕获值

Spring Boot Kotlin 数据类未使用 REST 控制器中的默认值初始化

使用 kotlin 流删除 map 中具有某些相似性的值

顶级属性的初始化

为什么 Kotlin 扩展运算符在传递原始可变参数时需要 toTypedArray()?

Kotlin 无法找到或加载主类

Koin Android:org.koin.error.NoBeanDefFoundException

在构造函数中仅注入某些参数

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

更新到版本4.10.1/4.10.2后 Gradle 同步失败

为什么 Kotlin Pair 中的条目不可变?

Android插件2.2.0-alpha1无法使用Kotlin编译

如何序列化/反序列化Kotlin密封类?

不推荐使用仅限生命周期的LifecycleEvent

具有泛型param的Kotlin抽象类和使用类型param的方法

Kotlin - 如果不为空,则使用修改后的 Obj props 覆盖 Obj props

尾随 lambda 语法(Kotlin)的目的是什么?