`var allByDefault:Int?`导致错误?

A.C*_*hao 5 kotlin

在kotlin引用的属性和字段中,编写了以下示例:

var allByDefault:Int?//错误:需要显式初始化程序,隐含默认的getter和setter

但是,我测试代码,编译和运行没有错误.这是我的代码"

fun main(args:Array<String>){
    var allByDefault:Int?
}
Run Code Online (Sandbox Code Playgroud)

那么为什么文档写道:

错误:需要显式初始化程序,隐含默认的getter和setter

我搜索谷歌寻求帮助,但没有找到任何可以帮助我的结果.


@toniedzwiedz的回答解决了这个问题.我的错.我误认为属性和变量.

ton*_*edz 9

fun main(args:Array<String>){
    var allByDefault:Int?
}
Run Code Online (Sandbox Code Playgroud)

你在这里拥有的是方法的var本地main,而不是属性.

class MyClass {

    //this is a property of MyClass that requires some means of initialization
    var allByDefault: Int? // Error: Property must be initialized or be abstract

    fun foo() {
       var local: Int? // this is a local variable defined in the scope of foo, which is fine
       // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 要添加到此:它仍然必须在第一次使用之前进行初始化,但是编译器允许您在没有初始值的情况下声明它,因为它可以检查它的所有用法是在初始化之后发生的 - 不像属性,可以从不同时间的各个地方.例如,这可以让你在`if-else`或`try-catch`中以不同的方式初始化它. (3认同)