Android Kotlin中具有2+;建设者
发现Android Kotlin中具有2+;建设者,android,kotlin,Android,Kotlin,发现init{}块在二级构造函数之前执行 所以基本上我有两个构造函数(primary和secondary)。主视图仅用于初始化简单视图。次要-尝试用数据填充EditView。在secondary构造函数之后,我希望执行init块 有没有办法让它发生 class EditView(val context: Context){ constructor(context: Context, title: String): this(context) { // Executes a
init{}
块在二级构造函数之前执行
所以基本上我有两个构造函数(primary
和secondary
)。主视图仅用于初始化简单视图。次要-尝试用数据填充EditView。在secondary
构造函数之后,我希望执行init
块
有没有办法让它发生
class EditView(val context: Context){
constructor(context: Context, title: String): this(context) {
// Executes after init block
}
init {
// Ran before secondary constructor
// Code for initializing my view
}
}
您不能这样做,因为
init
块本质上是主构造函数的主体(任何内联属性初始值设定项也是如此)。这意味着当您使用This(context)
从次构造函数调用主构造函数时,它将运行,只有这样,您才能在次构造函数中运行代码
首先运行主构造函数可以确保您的实例在主构造函数的主体运行时已处于有效的构造状态,例如,不可为null的属性具有非null值,等等。感谢您的精彩解释!