This post demonstrates how to overload class constructors in Kotlin
.
Requirements
IntelliJ
IDEA
Ultimate 2016.3- The
Community Edition
may be enough but we have not tried it.
- The
Kotlin
Version 1.1- Windows 10 Enterprise
[wp_ad_camp_1]
Primary vs Secondary Constructors
In simplest terms, the type of constructor in Kotlin
depends on where we declare/reference the constructor.
Below are examples of primary and secondary constructors. They are equivalent.
Primary Constructor Example
1 2 3 4 | // All class implicitly extend java.lang.Object class Parent(): Object() { // Other codes here } |
Secondary Constructor Example
[wp_ad_camp_2]
1 2 3 4 5 6 7 8 | // All classes implicitly extend java.lang.Object class Parent { constructor(): super() { // Other codes } // Other codes } |
Overloading Constructors
For instance, we have a class with overloaded constructors. Note, all classes implicitly extend from java.lang.Object
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class Base { /** * The compiler inserts a call to Object construct. For example, * * In Kotlin: * constructor():super() { } * * In Java: * * public Base() { super(); } * */ constructor() { } /** * The compiler inserts a call to Object construct. For example, * * In Kotlin: * constructor(p: String):super() { } * * to refer to the no-arg constructor of the current class: * * constructor(p: String):this() { } * * In Java: * * public Base(String p) { super(); } * * to refer to the no-arg constructor of the current class: * * public Base(String p) { this(); } * */ constructor(p: String): this() { } } |
[wp_ad_camp_3]
Using overloading constructors
1 2 3 4 5 6 7 8 | fun main(args: Array<String>) { var parent: Parent = Parent() var base1: Base = Base() var base2: Base = Base("base01") } |
[wp_ad_camp_4]