ref – https://www.programiz.com/kotlin-programming/constructors
In Kotlin, a class can also contain one or more secondary constructors. They are created using constructor keyword.
The most common use of secondary constructor comes up when you need to extend a class that provides multiple constructors that initialize the class in different ways.
For example, you want to initialize your class with absolutely no parameters. And then other instances where you want to initialize it with multiple parameters.
1 2 3 4 5 6 7 8 |
class Log { constructor(data: String) { // some code } constructor(data: String, numberOfData: Int) { // some code } } |
In our Log example, we have two secondary constructors. No primary constructor.
Constructor calling constructor
In Kotlin, you can also call a constructor from another constructor of the same class using this().
In our case, say for a 1 parameter constructor, we call a 2 parameter constructor right after the one parameter constructor finishes running.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Log { constructor(data: String) { // code } constructor(data: String, numberOfData: Int) { // code } } class AuthLog: Log { constructor(data: String): this(data, 10) { // code, this runs first, then calls the constructor with the two parameter below } constructor(data: String, numberOfData: Int): super(data, numberOfData) { // code, after running, calls Log's constructor } } |