AndroidKotlin

Multiple Constructors In Kotlin

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

Geethu is a teacher by profession, but she likes to research new things and is also interested in writing. Devdeeds is her blog, where she writes all the blog posts related to technology, gadgets, mobile apps, games, and related content.

Leave a Reply

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