那么init
不是构造函数的主体.它在具有主构造函数上下文的主构造函数之后调用.
As given in Official documentation:
主构造函数不能包含任何代码.初始化代码可以放在初始值设定项块中,其前缀为init关键字:
class Customer(name: String) {
init {
logger.info("Customer initialized with value ${name}")
}
}
请注意,可以在初始化块中使用主构造函数的参数.它们还可以在类主体中声明的属性初始值设定项中使用:
class Customer(name: String) {
val customerKey = name.toUpperCase()
}
事实上,为了声明属性并从主构造函数初始化它们,Kotlin有一个简洁的语法:
class Person(val firstName: String, val lastName: String, var age: Int) {
// ...
}
As per your question you can add a constructor to accept one parameter like following:
class Person(name: String, surname: String) {
constructor(name: String) : this(name, "") {
// constructor body
}
init {
Log.d("App", "Hello");
}
}
But it doesn't look right as we are unnecessary passing second argument empty string. So we can order constructor like following:
class Person(name: String) {
constructor(name: String, surname: String) : this(name) {
// constructor body
}
init {
Log.d("App", "Hello");
}
}
希望有帮助.