Multiple constructors in Kotlin

Kotlin is one of the most growing language and its official language for android application development. Today we will see one very important concept of kotlin i.r constructor.

Kotlin has two types of constructor

  • Primary constructor and
  • Secondary constructor

Primary constructor syntax

class Person constructor(name : String, age : Int)
//is same as 
class Person (name : String, age : Int)

Kotlin has default values property which is not there in Java, so it makes very easy for programmers to create constructors with very less boiler plate code, for ex

//In java
class View(Context context){}
class View(Context context, AttributeSet attributeSet){}
//The above two can be converted in one line in kotlin
class View(context:Context, attributeSet: AttributeSet? = null)

The above one is very useful but there are cases in which we cannot use default values for example let’s say we have some java class with three constructor as follow :

class Library{
Library(Context context){

}
Library(Context context, @NotNull String layoutId){}
}

class Something extends Library {
Something(Context context) {
super(context);
 }

Something(Context context, @NotNull String layoutId) {
super(context, layoutId);
 }
}

So what will we do? there comes the use of secondary constructor

Syntax for secondary constructor is:

class Person{
      constructor(name : String, age : Int)
}

How to overload multiple constructors ? The above can be solved as follow:

class Something : Library{
    constructor(context : Context):super(context)
    constructor(context : Context, @NotNull layoutId: String):super(context, layoutId)
}

Thanks for reading the post, I hope it helped you.

Add a Comment

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