Month: March 2018

One of the great things about Kotlin is its brevity and as part of that brevity, Kotlin works hard to eliminate what we often refer to as boilerplate code .. blocks of code that we frequently write with little or no change.

As great as Kotlin’s brevity is (and I do love it), it can often make understanding Kotlin challenging when first learning the language. Consider the following Kotlin class declaration:

In the Java version of the class, things become a bit more clear. We basically want the class to have 2 read-only properties (firstName, and lastName) and one read-write property (age).

As we look at the Java version of the class, we can see just how much boilerplate code is required. We have to declare private fields to store the firstName, lastName, and age; we create getter methods for the 2 read-only properties along with both a getter and setter for the read-write property. Then we have our constructor whose only real job is to accept initial values and then assign those values to the fields that correspond to our properties. That’s a lot of boilerplate code (property getters, property setters, and assignments to give properties their intial values).

A closer look at the Kotlin class declaration

To help us understand what’s happening in the Kotlin class, let’s look at a slightly more expressive way we can write the Kotlin class.

With this we can see our 3 properties a bit more clearly. By declaring firstName and lastName with “val” we’re indicating that they’re read-only properties (can’t be changed once initially set). Using “var” to declare age indicates that it’s a read-write property. So the “val” and “var” keywords allow us to create properties and indicate whether they’re read-only or read-write without having to write boilerplate getter/setter code as we did in Java.

The 3 values in the parenthesis after the class name are the class’ constructor parameters. As is often the case, the only purpose of those parameters is to receive the values that we’ll use to initialize the class properties.

Back to brevity

Since the only purpose of the constructor parameters is to initialize the properties, Kotlin allows us declare the properties themselves right there in the constructor parameter list. This allows us to get rid of the boilerplate code required to explicitly assign the constructor parameter values to the properties.

So with that in mind, we can go back our original Kotlin class declaration.

We declare a local variable named person and create a new instance of PersonKotlin passing initial values for the firstName, lastName, and age properties. We then use the firstName and lastName properties to create a string that says “Hello Maria Jones”. Finally, we celebrate Maria’s birthday by increasing the age property by one.

… and we get all of this from a Kotlin class that we can literally declare in a single line.