首页 > 解决方案 > 完成一些计算后从辅助构造函数调用主构造函数

问题描述

基本问题。我有一个主构造函数和一个辅助构造函数,在辅助构造函数中我计算/获取主构造函数

这是一个问题,因为据我所知,您需要立即在第二个内部调用主构造函数。

像这样

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 
    }
}

我最好的解决方案是简单地将空/空值发送到主构造函数,然后在构造函数的主体中更改它们

constructor(id: String) : this(null,0,null) {
   name = 
   age = 
   dateOfBirth = 
}

这行得通,但我想知道是否有更好的方法

很可能有一种更好的方法来构建整个事情,这将完全避免这个问题,所以如果是这样,请告诉我!

标签: kotlinconstructor

解决方案


您应该避免在构造函数内部使用任何计算。一般来说,这是一种不好的做法。我对您的建议是使用构建器函数。就像是:

class Test(
    var name: String,
    var age: String,
    var dateOfBirth: String) {
    companion object {
        fun fromId(id: Long): Test {
            //calculations
            return Test("", "", "")
        }
    }
}

推荐阅读