[英]Calling primary constructor from secondary constructor after some calculations are done
Basic question.基本问题。 I have a primary and secondary constructor, and inside the secondary constructor I calculate/fetch the primary constructors
我有一个主要和次要构造函数,在次要构造函数中我计算/获取主要构造函数
This is an issue since as far as I am aware you need to immediately call the primary constructor inside the second.这是一个问题,因为据我所知,您需要立即在第二个构造函数中调用主构造函数。
Like so像这样
constructor() : this(/*parameters for primary constructor*/)
However, I can't call the primary constructor because I don't know the parameters yet.但是,我不能调用主构造函数,因为我还不知道参数。
constructor() : this(/*???*/) {
//find parms of primary constructor
//i want to call primary constructor here
}
Is it possible to call the primary constructor later on in the secondary constructor?是否可以稍后在辅助构造函数中调用主构造函数?
Is there a better way to structure this to avoid the issue?有没有更好的方法来构建这个来避免这个问题?
Here is an oversimplified example这是一个过于简单的例子
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
}
}
My best solution was simply to send empty/null values to the primary constructor and then change them in the body of the constructor我最好的解决方案是简单地将空/空值发送到主构造函数,然后在构造函数的主体中更改它们
constructor(id: String) : this(null,0,null) {
name =
age =
dateOfBirth =
}
This works, but I was wondering if there is a better way这行得通,但我想知道是否有更好的方法
It is a definite possibility there is just a far better way to structure this whole thing, that would avoid this issue altogether, so let me know if that is the case!肯定有一种更好的方法来构建整个事情,这将完全避免这个问题,所以如果是这样的话请告诉我!
You do not need it all.你不需要这一切。 Declare variables in top level of class and set values after they are calculated.
在类的顶层声明变量并在计算后设置值。
class Sample(val n: Int, val m: Int) {
private val sum: Int
init {
sum = n + m
}
}
Then every time you initialize the class, the value of your variable will be calculated然后每次初始化类时,都会计算变量的值
You should avoid using any calculations inside of a constructor.您应该避免在构造函数中使用任何计算。 This is a bad practice in general.
这通常是一种不好的做法。 My suggestion for you is to use builder functions.
我对您的建议是使用构建器函数。 Something like:
就像是:
class Test(
var name: String,
var age: String,
var dateOfBirth: String) {
companion object {
fun fromId(id: Long): Test {
//calculations
return Test("", "", "")
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.