Android Pixel phone

Why you should use Kotlin for Android development

Java is the most widely used language for Android development, but that doesn’t mean it is always the best choice. Java is old, verbose, error-prone, and has been slow to modernize. Kotlin is a worthy alternative.

OpenJDK developers are starting to bridge the gap with Java 8,  but Android doesn’t use all the features of Java 8. Developers are still stuck in the old Java 7 and 6 worlds, and that's not going to improve much in the foreseeable future. That's where Kotlin comes in: This relatively new open source language, based on the Java Virtual Machine (JVM), is gaining traction with Android software engineers. 

There are other JVM languages you could try to use on Android, but Kotlin offers integrations with Android Studio, Google's primary IDE for Android, that no language, has, other than Java.

Here's why now is the time to start using this modern, sophisticated, pragmatic language for your Android development projects.

The Mobile Analytics Playbook: A Guide to Better Testing

What’s wrong with Java

You have probably been using Java for years (maybe for decades), so you are extremely familiar with it. You know the language from corner-to-corner, and you also several undocumented things that only veterans with years of experience have encountered.

So when a new language comes into town and someone tells you to switch to it, you're likely to be skeptical. I was too. But I have also used Java for a long time, and have developed a love-hate relationship with it.

I was not interested in switching away from Java at first, but when I started looking into Kolin and took notice of the bigger picture, I changed my mind. Here are a few of my reasons:

Java is old... very old

Java was one of the most usable languages, back in its heyday. But today, and the Java I use on Android doesn't even have support for lambdas, method references, streams, try-with-resources (minSdk ≥ 19). I still have to use the javax.time APIs from the old Java 6/7 worlds.

There are some third-party ways to backport some of these features using tools, such as RetroLambda, Streams backport, and ThreeTenABP, but that’s a hassle.

Android Nougat also made a bold attempt to support some Java 8 features using the Jack compiler, but most of those are only usable if you target minSdkVersion 24 -- something you shouldn’t do, considering how slow Android version updates have become.

Check out the platform version distribution chart here.

Java is error prone

One of the biggest flaws in Java is the way it handles “null,” leading to the dreaded NulPointerException (NPE),  popularly known as The Billion Dollar Mistake).

I call it my billion-dollar mistake. It was the invention of the null reference in 1965…This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years. — Sir Charles Antony Richard Hoare

Today, the NPE is one of the most common reasons for crashes in Android apps. In fact, it's almost impossible to have an app in production without a single NullPointerException (If you do, please tell me about it, I would be interested to hear how you avoided it).

And "nullability" is an even bigger problem for Android. Null is a very efficient and simple way of representing the absence of a value, and Android uses it in its framework and APIs. It's not good that Java makes it more difficult for developers to handle them.

A third problem has to do with the fact that programmers often ignore the way Java implements non-static inner classes and anonymous inner classes, which always keep an implicit reference to the outer class. In so doing, developers end up making their apps susceptible to memory leaks.

There's a whole wiki on Java's design flaws that I won't go into here, but I'll end on what might be the biggest gripe of all about Java:

Verbosity and ceremony

Developers love clean, concise code. Less code takes less time to write, less time to read, and is less susceptible to bugs. But with Java, you must write a lot of code to get even the simplest things done. You've probably already experienced this if you're an Android developer.

There's considerable “ceremony” involved in Java APIs, and Android makes that even worse by forcing developers to go through many steps, in a specific order, to get things done, such as accessing a database, handling fragment transactions, and so on.

If you could simplify a lot of these processes, it would improve your experience and productivity as an Android developer considerably.

Kotlin to the rescue

Java isn't the only language you can use to build Android apps. The most strongly supported JVM language in the Android ecosystem—aside from Java—is Kotlin, an open-source, statically-typed language developed by JetBrains. 

JetBrains created one of the most popular IDEs, IntelliJ IDEA, as well as Android Studio, which Google crowned as the standard IDE for Android development. It understood the pain developers face in day-to-day development workflow, and with Kotlin it has attempted to address those. JetBrains uses Kotlin in production to develop its own products, so it is unlikely that the language will suddenly be abandoned. 

Kotlin takes a pragmatic approach by not including features such as having its own build system or package manager because open source tools such as Gradle and Maven already handle this well. Having its own build system would have broken projects that already use Gradle and Maven.

Another pragmatic approach for Kotlin was to not re-implement the entire Java collections framework. That would have been easy, but the creators also wanted Kotlin to be compatible with the JDK collection interfaces without breaking any existing project implementations. 

One other huge benefit of Kotlin is that most of its language design decisions focused on maintaining backward compatibility with many Java and Android projects. For example, Kotlin still supports Java 6 bytecode because more than half Android devices still run on it. 

Kotlin is 100% interoperable with Java

This is the first thing I loved about Kotlin. You can call Java code from Kotlin and vice-versa seamlessly. Both Kotlin and Java generate the same bytecode, so there's no fear that you're shipping something completely different with Kotlin.

That means you can start using Kotlin in your existing project, with all your old Java code, right away. Start by writing some simple and small parts of your app in Kotlin as you start getting familiar with its constructs and syntax (which, by the way, is super-simple). 

I started using Kotlin for small parts of a large project, including a few UI components and simple business logic. Only four-to-five percent of the entire codebase was written in Kotlin; the rest is still in Java (which I plan to convert eventually).

This mix of Java and Kotlin code is working well in my project. Its interoperability is truly a blessing.

No more NullPointerExceptions

My team has been developing Android apps for three years, and NPE's have been one of the most common reasons for crashes in our apps.

It's been a major time investment to fix all of the NPEs that have come up, as guarding your code with null checks everywhere is a time consuming and boring task.

With Kotlin, you needn't worry about NPEs because null safety is baked into Kotlin's type system. It is so nice to catch NPEs at compile time instead of crashing apps at runtime.

How does this work in practice?  By default, all variables are non-null. If you want a "nullable" variable, you mark it with a “?”. Suppose you have a string variable and you are trying to assign a value to it:

var message: String message = “Have a great day”

That works great. Now, try to do this:

var message: String message = null

Here, the compiler fails to compile, instead giving you the message, “Null can not be a value of a non-null type String.” This happens because all variables default to non-null, and you have to explicitly tell the compiler that you want a nullable variable:

var message: String? message = null

Now it compiles fine, but you still must be careful while accessing this variable. With this type system in place, it will be very difficult for NPEs to occur in your app at runtime.

Great IDE and tooling support

You have very little to worry about in with continuing support, because a well-established company backs it. JetBrains specializes in creating some of the most used IDEs in the world. 

Refactoring support in  Android Studio

In Android Studio, all you have to do to get first-class Kotlin support is install this plugin. It’s that simple. It also offers an Eclipse plugin, if you are still using Eclipse (but seriously, why would you?).

All of Android Studio's IDE features work perfectly in Kotlin. You can mix and match Kotlin and Java code in the same project, and everything still works great. The IDE support for other JVM-based languages doesn't even come close.

Another amazing feature that the Kotlin plugin brings to Android Studio is the “Convert Java File to Kotlin” feature. Just give it your old Java file, and in one-click it will convert it to an equivalent Kotlin file. 

I have converted several Java files to Kotlin, and this feature worked well 99% of the time. 

Write less code, be happy

With Kotlin I write significantly less code than I ever wrote with Java. And fewer lines of code means smaller file sizes for Kotlin, compared to Java equivalents. I have converted several Java files of differing sizes into Kotlin using the Android Studio plugin, and I have yet to find a case where the file size wasn't smaller after the conversion. 

Kotlin is way more readable too, once you understand its syntax. It's not verbose, like Java. It is crisp, concise, and reduces a lot of much of the boilerplate code that developers must write every day. 

For instance, consider this click listener in Java. Everyone uses click listeners in their Android apps, but it takes a lot of code and ceremony in Java just to perform an action on the click of a button. view.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         // Do whatever you want to
}});

Now consider how you do it in Kotlin:

view.setOnClickListener { // Do whatever you want to }

See how simple and tight the syntax is? For more examples of Kotlin's conciseness, check out the language reference.

Kotlin is an enterprise language

Kotlin is not the new kid in town. It's been around for a few years, although it wasn't production ready until 2015. JetBrains developed it for solving practical, real-world development problems. And unlike other JVM-based languages, Kotlin doesn’t come from an academic or research background. It was built with the enterprise in mind.

It is always tempting to rebuild or re-implement everything from scratch. JetBrains could have done that with Kotlin, but it didn’t. Its goal was not to create something revolutionary, but to provide something that is usable and familiar to modern enterprise developers. 

Try it yourself

Kotlin can help make your life as an Android developer a lot easier. While developers sometimes go overboard when using cutting-edge technologies that aren't battle-hardened, new tools do get developers fired up to build awesome things. And with six years of development, Kotlin is on pretty solid footing.

To try it, open Android Studio, download the Kotlin plugin (works with Android Studio, not just IntelliJ IDEA), give it a go yourself, and let me know what you think.

The Mobile Analytics Playbook: A Guide to Better Testing

Image credit: Flickr

Topics: Mobile