Kotlin: 33% shorter, loads more fun!
Java, Kotlin or Dart? One App, three implementations.
Part 2: Kotlin
In this installment of our series, we look at the Kotlin implementation of IndoFlash — and it is beautiful! It is smaller by about a third, much easier to understand, and has been checked by a stronger compiler, so will be less likely to contain bugs. There are no downsides at all to using Kotlin. I thoroughly recommend it as a language for Android development.
The improvements over the Java version are due to two things. First, Kotlin is an extremely expressive and powerful language: once you’ve worked with it for a while, going back to older languages is just painful. Second, JetBrains have built a great library, called Anko, that contains all sorts of tools for simplifying common tasks. Let’s first look at what the language gives us.
Note: Read Part 1 of this series for an overview of IndoFlash.
The power of Kotlin
Data classes
The Kotlin compiler writes a lot of code for us, and there is no better example of this than the Word class:
data class Word(val word: String, val definition: String)This single line replaces about twenty lines of boilerplate Java. Hard to beat!
Immutable types
The WordList class returns a list of Words that to be displayed. We want the returned list to be immutable. In Java the words() method is
public List<Word> words() {
return Collections.unmodifiableList(words);
}The specification that the returned list is immutable is expressed as a unit test:
@Test(expected = UnsupportedOperationException.class)
public void wordsIsImmutable() {
wl123().words().add(new Word(“empat”, “four”));
}In Kotlin, the function can be written to return an immutable type:
fun words(): List<Word> = words.toList()The toList() function returns a List, which is immutable. It’s not possible to compile code that attempts to change the return of words(). So the test cannot even be written. The compiler is doing this test for us.
By the way, that is the entire function: we don’t need braces for one-liners, and the return type is inferred. There is a very high signal-to-noise ratio in Kotlin. It’s lovely!
More Kotlin goodness
Here’s the WordList function for persistence to disc:
fun store(writer: Writer) {
val bw = BufferedWriter(writer)
words.forEach{ bw.append(“${it.word}=${it.definition}\n”) }
bw.close()
}The middle line shows a few nice things:
- the use of an anonymous function,
- if we refer to the loop variable as
it, then it does not need an explicit declaration, which is a really practical bit of syntax that reduces code bloat, Stringinterpolation,- safe access to the properties of the data class
Word, and - clutter-free exception handling.
Extension functions
One of the really practical features of Kotlin is extension functions. These allow us to effectively add new methods to an existing API. For example, here’s some code for deserialising the XML document that defines a list of chapters in IndoFlash:
document.getElementsByTagName(CHAPTER).iterable().forEach {
tempList.add(ChapterSpec(it as Element))
}In this code, document is a W3C Document object, which is part of a very tired API that certainly doesn’t include the iterable() function. So what’s happening here? In fact, the iterable() in this code is an extension function which is declared as a top-level function and can be used as if it were an instance function:
fun NodeList.iterable(): Iterable<Node> {
val result = mutableListOf<Node>()
for (i in 0..this.length — 1) {
result.add(this.item(i))
}
return result.asIterable()
}This certainly makes XML processing less of a drag!
The Anko library
We could go on for ages about the expressive power of Kotlin, but others have already done that! So let’s have a brief look at the Anko library.
As an example of how powerful Anko is, consider first this Java code to show an Alert:
private void showHelp() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Add the buttons
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
}); builder.setTitle(getApplicationContext().getResources().getString(R.string.help));
builder.setMessage(getApplicationContext().getResources().getString(R.string.help_text));
//Create the AlertDialog
AlertDialog dialog = builder.create();
dialog.show();
}Horrible, isn’t it? Well, using Anko, we can simply write:
alert(R.string.help_text, R.string.help) { yesButton { } }.show()Now, some will cry “But three three of the Java lines are comments, so it’s not a fair comparison!”. Well that’s sort of true, but the fact is that the comments are required to highlight meaningful statements otherwise lost in the boilerplate.
The Anko example shown above uses a Domain Specific Language (DSL) to define what the yes button does. In fact, Anko can be used to build the entire user interface. Here’s the complete implementation of WordListSelecter:

The code beginning with verticalLayout on line 26 is Anko DSL for building the user interface. It takes the place of the usual XML layout for an Activity. So the code is short, and we no longer need the XML layout document. And let’s face it, the world is always a better place when we can delete some XML!
Conclusion
As you can see, once you start using Kotlin, almost every aspect of your programming life will improve! It’s really easy to get started with Kotlin and it is an immense pleasure to progam in such a well designed language.
The Kotlin version of IndoFlash can be downloaded from
The Java version is available from
