· 5 min read
Kotlin for Android (I): Introduction
Kotlin is one of the many JVM based languages that are starting to emerge as a possible Java successor in Android development. Java is one of the most used languages in the world, and while many other languages evolve to make programmers lives easier, Java has not been able to keep their track as fast as expected.
It seems that many of the things Java lacks are being covered in latest revision, but Android developers won´t be able to take advantage of them for many years. That´s the interest behind the use of Kotlin and similar languages: being able to use modern programming techniques in our ancient environment.
What´s Kotlin?
Kotlin is a JVM based language created by JetBrains, the team behind IntelliJ, which is the base for Android Studio. It´s an object oriented language that includes many ideas from functional programming.
Kotlin was born with the idea of covering those gaps Java leaves and add much more simplicity to the code saving us from writing as much boilerplate code as possible.
Why Kotlin?
My first disclaimer is that I haven´t tried any other alternatives to Kotlin such as Go or Scala, so I recommend searching what other people thinks about those languages if you are really thinking on switching to another language. An awesome example of Android using Scala can be found in 47deg Github site.
These are the reasons why I chose Kotlin as a study case:
- Relatively fast learning curve: compared to Scala for instance, we are moving in a much simpler scope. Kotlin is much more limited, but it´s easier to start if you´ve never used a modern language before.
- Lightweight: Kotlin library is small compared to others. This is important because Android method limit is always a problem, and though there are some options to solve it such as proguard or multidexing, all of these solutions will add complexity and will be time consuming when debugging. Kotlin adds less than 7000 methods, more or less the same as support-v4.
- Highly interoperable: It works extremely well with any other Java libraries, and the interoperability is very simple. That´s one of the main ideas the Kotlin team kept in mind while developing this new language. They want to use it to continue developing their current projects written in Java without having to rewrite the whole code. So Kotlin needs to be extremely interoperable with Java code.
- Perfectly integrated with Android Studio and Gradle: we have one plugin for the IDE and another one for Gradle, so it won´t be difficult to start an Android project using Kotlin (this is what I´ll talk about in the next article).
An interesting document I recommend reading before taking any decision is the one Jake Wharton wrote about the use of Kotlin for Android development.
What do we get with Kotlin?
1. Expressiveness
With Kotlin, it´s much easier to avoid boilerplate because most typical situations are covered by default in the language.
For instance, in Java, if we want to create a typical data class, we´ll need to write (or at least generate) this code:
public class Artist {
private long id;
private String name;
private String url;
private String mbid;
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
public String getMbid() { return mbid; }
public void setMbid(String mbid) { this.mbid = mbid; }
@Override
public String toString() {
return "Artist{" + "id=" + id + ", name='" + name + '\\'' + ", url='" + url + '\\'' + ", mbid='" + mbid + '\\'' + '}';
}
}
How much code is this on Kotlin? Just this simple data class:
data class Artist(
var id: Long,
var name: String,
var url: String,
var mbid: String
)
2. Null safety
When we develop using Java, most of our code is defensive. We need to check continuously if something is null before using it if we don´t want to find unexpected NullPointerException. Kotlin, as many other languages, is null safe because we need to explicitly specify if an object can be null by using the safe call operator.
We can do things like this:
//This won´t compile. Artist can´t be null
var notNullArtist: Artist = null
//Artist can be null
var artist: Artist? = null
// Won´t compile, artist could be null and we need to deal with that
artist.print()
// Will print only if artist != null
artist?.print()
// Smart cast. We don´t need to use safe call operator if we previously checked nullity
if (artist != null) {
artist.print()
}
// Only use it when we are sure it´s not null. Will throw an exception otherwise.
artist!!.print()
// Use Elvis operator to give an alternative in case the object is null
val name = artist?.name ?: "empty"
3. Extension functions
We can add new functions to any class. It´s a much more readable substitute to the typical utility classes we all have in our projects. We could, for instance, add a new method to fragments to show a toast:
fun Fragment.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(getActivity(), message, duration).show()
}
We could now do:
fragment.toast("Hello world!")
4. Functional support (Lambdas)
What if instead of having to write the creation of a new listener every time we need to declare what a click should do, we could just define what we want to do? We can indeed. This (and many more interesting things) is what we get thanks to lambda usage:
view.setOnClickListener { toast("Hello world!") }
Conclusion
Kotlin is a very interesting alternative to Java for developing Android apps. Next articles will describe how to start a new project using Kotlin, and how to take the most out of the language to make Android development easier. Stay tuned!