For Android developers there is a shift going on from Java to Kotlin. Here we are going to look at some Kotlin features that caught my eye. My overall impression is that it’s Java but more concise and more safe. Let’s have a look.
For more documentation, examples and background go to the Kotlin site.
Before diving into the features of Kotlin it is good to note that it has great interoperability with Java. So migration can be done in steps. For example I started with only migrating the domain model packages with the POJO’s. This brings us to the first feature.
A lot of Java code surrounding POJO’s is named boilerplate code. Such as getters, setters or toString methods. Kotlin removes this with the data class.
Note that you can define default values for the constructor arguments as shown above. For all functions Kotlin supports calling them with named arguments. This can be done in any order. The following instantiates a valid Person object.
If you know what the form is of your objects you can deconstruct them into their parts. This is very useful in lambda’s for example.
Checking if an object is not null is common practice in Java to avoid the feared
. In Kotlin this defined in the type so not null can be enforced by the compiler.
So the nullability is captured by the type. Furthermore there are operators for these nullable types. Take a look at the following:
The maximum of the prices of the items may not exist. The
will not throw an exception if it is not there. Only if the item exists the price will be returned. If there is no maximum item the
will default to 0.
With Java 8 streams are very much present in the language. But for collections there still has to be a transformation
. In Kotlin these operators are available on the collections.
NOTE: The resulting stream pipeline is NOT lazy like in Java! Every operator will form a new collection beginning at the top and pushed down.
There are a lot of Kotlin features we did not discuss. Features like higher order functions or the delegation pattern. These are not less cool but for the sake of time they may be found in later posts.
Hopefully you got a taste of some cool features of Kotlin. For me these were the main reasons to look at migrating from Java to Kotlin. Happy coding!