小编Ebn*_*ang的帖子

Kotlin在声明之前初始化变量?

这是我的测试代码:

class Test {
    init {
        a = 1
    }

    constructor() {
        a = 2
    }

    private var a: Int

    init {
        a = 3
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我删除辅助构造函数:

class Test {
    init {
        a = 1 // Error: Variable cannot be initialized before declaration
    }

//    constructor() {
//        a = 2
//    }

    private var a: Int

    init {
        a = 3
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道

在实例初始化期间,初始化程序块的执行顺序与它们在类主体中出现的顺序相同.

但是,如果存在辅助构造函数,为什么我可以在声明之前初始化变量?


更新:

我发现了一件有趣的事:

class Test {
    init {
        a = log(1)
    }

    constructor() …
Run Code Online (Sandbox Code Playgroud)

constructor initialization declaration kotlin

18
推荐指数
1
解决办法
1999
查看次数

标签 统计

constructor ×1

declaration ×1

initialization ×1

kotlin ×1