Software Development

Kotlin – Overloading Constructors

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.
  • 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

Secondary Constructor Example

[wp_ad_camp_2]

Overloading Constructors

For instance, we have a class with overloaded constructors. Note, all classes implicitly extend from java.lang.Object.

[wp_ad_camp_3]

Using overloading constructors

[wp_ad_camp_4]

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like