Ad Infinitum
Ad Infinitum

Reputation: 3696

Multiple constructor in the base class and call the most suitable one from the derived class in Kotlin

I have a base class with two constructors, which accepts errorMessage and errorCode. errorMessage is mandatory but errorCode is not.

class FooBaseClass{

constructor(errorMessage: String)                   // 1. Constructor
constructor(errorMessage: String, errorCode: Int)   // 2. Constructor

}

and a derived class with primary constructor

class FooDerivedClass(errorMessage: String, errorCode: Int) :
FooBaseClass(errorMessage, errorCode)

I want to design the constructor of my derived class as follows;

if the system provides only errorMessage, i want to call the 1.Constructor in the base class. If the system provides both parameters, i want to call the 2.Constructor.

What kind of design solution would suit here as the best solution?

Upvotes: 2

Views: 629

Answers (1)

Sam
Sam

Reputation: 5392

Well you call the overload you need, it's pretty straight forward.

OPTION 1

class FooBaseClass{
    constructor(errorMessage: String){

    }                   
    constructor(errorMessage: String, errorCode: Int){

    }
}

class FooDerivedClass : FooBaseClass{
     constructor(errorMessage: String) : super(errorMessage)
     constructor(errorMessage: String, errorCode: Int : super(errorMessage, errorCode)
}

I would also say if you aren't doing independent things in those constructors it would be easier to use defaults like.

OPTION 2

class FooBaseClass{                  
    constructor(errorMessage: String, errorCode: Int? = null){
        if(errorCode != null){
            //use it
        }
    }
}

class FooDerivedClass : FooBaseClass{
   constructor(errorMessage: String, errorCode: Int? = null : super(errorMessage, errorCode)
}

Just a suggestion. And you can take it one step further, if there is only one constructor you can simply do the default constructor like:

OPTION 3

class FooBaseClass(errorMessage: String, errorCode: Int? = null){
    val errStr: String = errorMessage
    val errCode: Int? = errorCode        
}

class FooDerivedClass
    constructor(errorMessage: String, errorCode: Int? = null : super(errorMessage, errorCode){

}

NOTE* Storing in local variables is only necessary if you are doing get/set databinding, or other annotations that require a variable to add onto.

Happy Coding

Upvotes: 3

Related Questions