完成一些计算后从辅助构造函数调用主构造函数
Calling primary constructor from secondary constructor after some calculations are done
基本问题。我有一个主要和次要构造函数,在次要构造函数中我 calculate/fetch 主要构造函数
这是一个问题,因为据我所知,您需要立即调用第二个构造函数中的主构造函数。
像这样
constructor() : this(/*parameters for primary constructor*/)
但是,我还不能调用主构造函数,因为我还不知道参数。
constructor() : this(/*???*/) {
//find parms of primary constructor
//i want to call primary constructor here
}
是否可以稍后在辅助构造函数中调用主构造函数?
是否有更好的结构来避免这个问题?
这是一个过于简单的例子
class Test(var name: String,var age: String,var dateOfBirth: String){
constructor(id: String) : this(/*???*/) {
//get name, age, dob, from id
I want to call the primary constructor here since
}
}
我最好的解决方案是简单地将 empty/null 值发送到主构造函数,然后在构造函数的主体中更改它们
constructor(id: String) : this(null,0,null) {
name =
age =
dateOfBirth =
}
这行得通,但我想知道是否有更好的方法
很可能有更好的方法来构建整个事情,这将完全避免这个问题,所以如果是这样的话请告诉我!
您应该避免在构造函数内部使用任何计算。这通常是一种不好的做法。我对你的建议是使用构建器函数。类似于:
class Test(
var name: String,
var age: String,
var dateOfBirth: String) {
companion object {
fun fromId(id: Long): Test {
//calculations
return Test("", "", "")
}
}
}
基本问题。我有一个主要和次要构造函数,在次要构造函数中我 calculate/fetch 主要构造函数
这是一个问题,因为据我所知,您需要立即调用第二个构造函数中的主构造函数。
像这样
constructor() : this(/*parameters for primary constructor*/)
但是,我还不能调用主构造函数,因为我还不知道参数。
constructor() : this(/*???*/) {
//find parms of primary constructor
//i want to call primary constructor here
}
是否可以稍后在辅助构造函数中调用主构造函数?
是否有更好的结构来避免这个问题?
这是一个过于简单的例子
class Test(var name: String,var age: String,var dateOfBirth: String){
constructor(id: String) : this(/*???*/) {
//get name, age, dob, from id
I want to call the primary constructor here since
}
}
我最好的解决方案是简单地将 empty/null 值发送到主构造函数,然后在构造函数的主体中更改它们
constructor(id: String) : this(null,0,null) {
name =
age =
dateOfBirth =
}
这行得通,但我想知道是否有更好的方法
很可能有更好的方法来构建整个事情,这将完全避免这个问题,所以如果是这样的话请告诉我!
您应该避免在构造函数内部使用任何计算。这通常是一种不好的做法。我对你的建议是使用构建器函数。类似于:
class Test(
var name: String,
var age: String,
var dateOfBirth: String) {
companion object {
fun fromId(id: Long): Test {
//calculations
return Test("", "", "")
}
}
}