x Of my Favorite Kotlin Features over Java

Kotlin is a fairly new programming language, with work starting on it in 2011 and it’s first (stable) release in 2016. It’s main purpose it to output JVM bytecode (meaning it compiles the same way as Java) with special aim towards the Android+Gradle platform. It’s one of the few programming languages who’s main purpose was to become cleaner, easier to write, and easier to maintain. They’ve introduced features for many different annoyances that exist in Java.

There are too many features to go over in one article, so here are a few of my favorite (and why I use Kotlin over Java in all of my projects):Singleton ClassesJava is an Object Oriented Language, meaning everything works in instances of classes (objects). However, sometimes you need a single class instance that manages everything (things like MySQL connection pooling, flatfile data parsers, etc). In Java, you should have a single instance of this manager object. To always keep a reference to this single instance, you can set a final static variable of the instance inside the class referencing an instance of itself (created only once).

Some methods also only create the object when it’s needed, so the object isn’t created when it isn’t ever used. These type of classes are called singleton classes, and look something like this:

The doFunction() function can be called from anywhere with SingletonExample.getInstance().doFunction(), and the instance of the object is only created when used the first time. Kotlin, however, has a feature called “object” which creates the instance automatically without having to make any call to getInstance().

The same singleton class in Kotlin looks like this:

The doFunction() function can be called with SingletonExample.doFunction(), making each call to the instance that much shorter. Now, because Kotlin cannot introduce any new features into the bytecode, when it gets compiled it will do the same thing as the first example. However, the code becomes much easier to write, if not giving a performance boost.

Leave a Reply

Your email address will not be published. Required fields are marked *