Skip to content

Multiple Constructors In Kotlin

  • by

In some cases when we need to use a class with different objects as its constructor argument. In such case we have to create multiple constructors. In Kotlin there is a predefined constructor called primary constructor which can either be an empty or with arguments.

Primary Constructor or Default Constructor

This is normal way in which we create a constructor. In this case SampleClass expects only one type of argument.

class SampleClass(context: Context) { 
var mContext = context

  //Rest of the code in the class
}

Multiple Constructors

In this case we have two constructors with different types of arguments. Let’s see how we define them.

class SampleClass() {

 var mApp: Application? = null
 lateinit var mContext: Context

constructor (app: Application) : this() {
        mApp = app
        mContext = app.applicationContext
    }

constructor(context: Context) : this() {
        mContext = context
    }

    //Rest of the code in the class
}

Leave a Reply

Your email address will not be published. Required fields are marked *