At Google I/O 2017 Google announced official support for the Kotlin programming language. Mostly because Kotlin is a friendly modern language with immense expressive power, functional programming capabilities, lambda functions support, powerful type-inference and analysis capabilities with quite ergonomic syntactic sugar.

Why Kotlin?

The language has been in development for a few years now and has interoperability with existing Java code so you can call Java code from Kotlin and vice-versa. It has excellent tooling support with Android Studio and Gradle plugins as well as debugger integration.

How Twilio Uses Kotlin

The Twilio Chat Android SDK was written in Java with some JNI bridging to C libraries provided by Twilio to give a handy package with native look and feel.

The Chat Demo application was also written in Java which made it a hard to follow with all the Chat SDK usage details behind a lot of Java boilerplate.

So we set a goal to fix this and make the demo application more transparent so users could focus on SDK usage examples rather than trying to untangle Java code.

A longer-term goal is to convert the SDK code to Kotlin to reduce the boilerplate amount and improve maintainability.

How we did it?

First we installed the new Android Studio 3.0 – it looks much cleaner than the old 2.0 series and also has fully functional support for Kotlin.

Then, open a Java project with it and go to Tools > Kotlin > Configure Kotlin in project command. This will add directives to enable Kotlin support in the project and synchronize it with these changes. Now we’re able to write and compile Kotlin.

Now for the the most exciting part. Open any Java file in the project and go to Code > Convert Java File to Kotlin File . This will automatically convert the Java code to Kotlin.

The conversion process tries to stay as close to original Java structure as possible while also using several idiomatic Kotlin constructs to make the code cleaner.

The result output of the plugin can be immediately compiled, so you can test conversion file-by-file.

Interesting parts

Refactoring Java code to Kotlin conventions

While direct automatic translation is easy, Kotlin has a few idiomatic approaches to coding that may help produce cleaner code.

Autogenerated UI element accessors

Let’s look at this code as an example. Synthetic properties generated by Kotlin let you access your XML-defined elements by their ID as if they were normal constants in your code. See usage examples here and here.

apply() is great!

apply() is an extension method available for all classes. It simply captures the object and lets you execute a block of code within this object’s context so the following Java code: