我们需要在Kotlin中初始化可为空的字段吗?

Sam*_*ıcı 5 nullable kotlin

我最近查看了一些kotlin代码,将所有可为空的字段初始化为null。

val x : String? = null和之间有什么区别val x : String?

我们应该将可为空的字段初始化为null吗?

Zoe*_*Zoe 9

所有东西,甚至可以为空的变量和原语,都需要在 Kotlin 中初始化。正如 tynn 提到的,如果您需要覆盖,您可以将它们标记为抽象。但是,如果您有接口,则不必初始化它们。这不会编译:

class Whatever {
    private var x: String? 
}
Run Code Online (Sandbox Code Playgroud)

但这将:

interface IWhatever {
    protected var x: String?
}
Run Code Online (Sandbox Code Playgroud)

这个也是:

abstract class Whatever {
    protected abstract var x: String?
}
Run Code Online (Sandbox Code Playgroud)

如果它是在方法中声明的,则不必直接对其进行初始化,只要在访问之前对其进行初始化即可。如果您熟悉 Java,这与在 Java 中完全相同。

如果你没有在构造函数中初始化它,你需要使用lateinit. 或者,如果您有val,则可以覆盖get

val something: String?
    get() = "Some fallback. This doesn't need initialization because the getter is overridden, but if you use a different field here, you naturally need to initialize that"
Run Code Online (Sandbox Code Playgroud)

正如我打开的那样,即使是可为空的变量也需要初始化。这就是 Kotlin 的设计方式,而且没有其他办法。所以是的,如果您不立即用其他东西初始化它,您需要将字符串显式初始化为 null。