Tag: 初始化

初始块位置在Kotlin上课

我最近遇到了一种情况,我的标准variables的值被默认值所替代,即使我已经使用init块的构造函数赋值了。 我试过的是: class Example(function: Example.() -> Unit) { init { function() } var name = “default name” } // assigning it like this: val example = Example { name = “new name” } // print value print(example.name) // prints “default name” 在挣扎了一下之后,我发现init块的位置很重要。 如果我把init块放在类的最后一个,它首先用缺省值初始化名称,然后调用用“new name”替换值的函数()。 如果我把它放在第一,它没有find名称,它被替换为“默认名称”时,属性被初始化。 这对我来说很奇怪 任何人都可以解释为什么发生这种事

Kotlin在声明之前初始化一个variables?

这是我的测试代码: class Test { init { a = 1 } constructor() { a = 2 } private var a: Int init { a = 3 } } 如果我删除了第二个构造函数: class Test { init { a = 1 // Error: Variable cannot be initialized before declaration } // constructor() { // a = 2 // } private […]

Kotlin构造函数中的语句

有没有办法在Kotlin中混合语句(如打印语句)和成员分配? 这里是我想要做的一个例子(用Java): class MySystem { ComponentA componentA; ComponentB componentB; public MySystem() { System.out.println(“Initializing components”); this.componentA = new ComponentA(); System.out.println(“Constructed componentA”); this.componentB = new ComponentB(); System.out.println(“Constructed componentB”); } } 感谢任何输入,谢谢。