Home > OS >  Calling primary constructor from secondary constructor after some calculations are done
Calling primary constructor from secondary constructor after some calculations are done

Time:10-28

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!

CodePudding user response:

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("", "", "")
        }
    }
}

CodePudding user response:

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

  • Related