Primary and secondary constructors in Kotlin

Ladies and Gents, given is just a quick example of overloaded constructors in kotlin language. Let’s first take a look at sample code that will demonstrate usage of primary and secondary constructors:

Here we defined sample kotlin class Hotel with total of 2 constructors:

  • with name, city and stars arguments
  • with jimIncluded added on top of previous one

If kotlin class has defined primary constructor, each secondary constructor is obliged to call that constructor either directly or indirectly via one of defined secondary constructors, in the following manner: constructor(first: String, second: String, third: String) : this(first, second) { … }

We can see both examples, not having primary constructor (h1.kts Gist), and one having (h2.kts Gist), and how we achieve similar functionality using either of them.

Primary constructors have the advantage of having ability to use val keyword, and thus being able to directly define class properties. Secondary constructors can’t use val keyword in their argument list.

That was it for today.

In case you liked this post – feel free to subscribe for more interesting content coming up!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s