为什么Kotlin编译器需要var属性的显式初始化程序? [英] Why Kotlin compiler requires the explicit initializer of var property?

查看:296
本文介绍了为什么Kotlin编译器需要var属性的显式初始化程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解以下Kotlin文档:

I can't understand the following piece of Kotlin documentation:

The initializer, getter and setter are optional. Property type is optional
if it can be inferred from the initializer or from the base class member being overridden.

Examples:
var allByDefault: Int? // error: explicit initializer required, default 
getter and setter implied

这里为什么编译器需要显式初始化程序的唯一解释(至少我可以提出的唯一解释)是Kotlin没有属性的默认值.这样对吗?如果是这样,为什么?换句话说:Kotlin属性和Java字段(具有默认值)之间的区别是什么,不允许我们使用属性的默认值?

The only explanation of why the compiler requires explicit initializer here (at least the only explanation I can come up with) is that Kotlin does not have default values of properties. Is it right? If so, why? In other words: what is the difference between Kotlin properties and Java fields (which have default values) which doesn't allow us to have default values of properties?

推荐答案

这很简单:在Java中,默认值为0(零)和null.但是在Kotlin中,大多数值都是不可为空的,因此您不能使用null对其进行初始化.对于原始值,可能有一个默认的用零初始化的策略,但是为了保持一致而没有这样做.但是在原始数组中,默认值确实为零.

That's simple: in Java default values are 0 (zero) and null. But in Kotlin most of the values are not-nullable, so you can't initialise them with null. For primitive values there could be a default strategy of initialising with zeros, but it was not done in order to be consistent. But in primitive arrays the default value is zero indeed.

如果您确实需要初始化语义,请查看lateinit属性:

If you really need that initialisation semantic, take a look at lateinit properties: https://kotlinlang.org/docs/reference/properties.html#late-initialized-properties.

该机制基本上允许使用null初始化字段,但随后将您从null断言中解放出来.

That mechanism basically allows to init a field with null, but then frees you from null assertions.

添加

实际上,科特林对初始化非常聪明.例如,有效的方法:

Actually Kotlin is very clever about initialization. For example that works:

val x: Int

if(something)
    x = 1
else
    x = 2

println(x)

在这里,kotlinc可能会证明x在使用之前被初始化 ,所以代码还可以

Here kotlinc may proove that x is being initialized before it is being used, so the code is OK

这篇关于为什么Kotlin编译器需要var属性的显式初始化程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆