Kotlin is relatively new language developed by JetBrains, released at the beginning of 2015. It comes from the industry and is developed for the industry, it solves a lot of problems we are facing today, like null pointer exceptions. The language and all its features are working with JVM and are compatible and fully interoperable with Java 6, which makes it a great tool for Android development.

We can read that Kotlin is

“a statically typed language that targets the JVM and JavaScript. It is a general-purpose language intended for industry use”.

People at JetBrains put a great effort to address some of the Java limitations, making Kotlin more and more tempting for Android developers to pick up. Thanks to the JetBrains’ Kotlin plugin for Android Studio, integrating IDE with the language and the project itself is dead easy. It has been described in the tutorial on the official Kotlin website. It is common misconception that by using Kotlin you need to get rid of all the libraries you are currently using. This is not true. In fact, thanks to the fully interoperability with Java, you can use all of the libraries written in Java that exist in your project, directly from Kotlin.

In the article, I’ve decided to describe few of the features that Kotlin brings to the table, as well as the verbose differences between Java and Kotlin, which hopefully will convince you to try it out. Full list of Kotlin features and addressed Java issues, with the description is available in the language reference docs.

Kotlin is small

The Kotlin library is really small. According to the tests, including Kotlin in your project will increase the size of your APK by 341KB, which is often the size of typical Android library. The method count will also increase by 6063, which seems to be a lot, but if we think about Guava (~15k methods) or other libraries like Google Play Services, that doesn’t seem that many. Kotlin works also really well with ProGuard. Empty Android project with ProGuard enabled will reduce Kotlin library size to 3KB and methods overhead to 42. It is worth mentioning that Kotlin can succesufuly replace a lot of libraries you are currently using with just a few lines of code thanks to the build-in language features.

Kotlin has a support

Kotlin has been well-received by the community. You can find a lot of Kotlin-related libraries in the GitHub repository, and every day a lot of new tools appears. At the moment, you can easily find frameworks for most popular things like Rx, Data Binding, Dependency Injection, and a lot more. This of course doesn’t mean that you can’t use well known Dagger 2 written in Java in your Kotlin project! One of the most popular libraries for JetBrains language is Anko, which reduces a lot of boiler plate from the code, allowing us, developers, to develop faster and more efficiently.

Kotlin is expressive

One of the most awesome features of Kotlin is how intuitive the syntax is. It is really easy to switch from Java to Kotlin and get used to the new syntax. All the language features will surely come one by one and I assure you, you will appreciate most of them : )

When

In Kotlin, Java switch block has been replaced by when expression and the syntax is as follows:

when (x)  {
    0, 1 -> print("x == 0 or x == 1")
    else -> print("otherwise")
 }
when (x) { 
    in 1..10 -> print("x is in the range") 
    in validNumbers -> print("x is valid") 
    !in 10..20 -> print("x is outside the range") 
    else -> print("none of the above") 
}

also, thanks to the smart cast, you don’t need any additional cast after you value type.

val hasPrefix = when(x) { 
    is String -> x.startsWith("prefix") 
    else -> false 
}
For loop

for loop in Kotlin is really simple. You can have access to the item, index, or both.

for (item in collection) print(item)
for (i in array.indices) print(array[i]) 
for ((index, value) in array.withIndex()) { 
    println("the element at $index is $value") 
}
If expression

In Kotlin there is no need for ternary operator since if is an expression, which means it can return a value. It allows you to use expressions like:

val max = if (a > b) a else b
A lot less ceremony in code

Kotlin allows us to type less. Simple functions are really simple. For example, instead of:

int sum(int a, int b) {
    return a + b
}

we can type:

fun sum(a: Int, b: Int) = a + b

Notice that we don’t need to declare the return type, it is inferred by the compilator. We can also take advantage of string interpolation to print or log message more easily, so instead of:

Log.d(TAG, “Multiplication of “ + first + “ and “ + second + “ resulted in: “ + result); 

we can use:

Log.d(TAG, “Multiplication of $first and $second resulted in: $result”); 

Higher-Order funcions are functions that take funcions as a parameters or returns a function. They often allow us to get rid of a lot of boiler plate code. One of the typical examples would be setting onClickListener to a button. In Java we would have to type:

button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        // code here.
        Toast.makeText(this.MainActivity, "button clicked", Toast.LENGTH_LONG).show();
    }
});

Where in Kotlin we can simply:

button.setOnClickListener {
    // code here
    Toast.makeText(this, "button clicked", Toast.LENGTH_LONG).show()
}

or, if we use Anko which provides a lot of really useful extension functions, described later in the article!

button.setOnClickListener { toast("button clicked") }

If you are using library like Butter Knife, you can simply remove it from the project, since it is no longer needed, listeners are easily covered now. What about binding views? Check Kotlin Android Extensions!

Obviously, there is a lot more of cool stuff related to Kotlin syntax. I encourage you to check it by yourself in the language documentation, which is really well crafted.

Kotlin Android Extensions

Every Android developer knows what is findViewById(), and probably doesn’t like it too much. There are libraries like Butter Knife which allow us to bind the views easier by using annotations, but with Kotlin you don’t really need any of them. With Android Extensions you can easily access the views from your .xml. You can do it like so:

// Using R.layout.activity_main from the main source set 
import kotlinx.android.synthetic.main.activity_main.* 

class MyActivity : Activity() { 
    override fun onCreate(savedInstanceState: Bundle?) { 
        super.onCreate(savedInstanceState)         
        setContentView(R.layout.activity_main) 
        textView.setText("Hello, world!") 
    } 
}

Null safety

Kotlin provides null safety mechanism which handles the issue of null reference exception, which is a huge deal. Every object declaration contains information whether the variable can be null or not, which is distinguished by question mark - ?. Object that cannot be null would look like this:

var name: String = "Natalie" 
name = null // compilation error
name.length // OK

nullable variable would be declared this way:

var name: String? = "Natalie" 
name = null // OK
name.length // compilation error

If we want to access nullable object method or property, we can explicitly check if it is null with if expression, or use safe call operator which return null if object we are calling is actually a null.

name?.length // OK

There is a lot more to say about the way null safety is handled in the specific cases and what are its limitations. You can read the Null Safety related docs to check it out!

Optional and named arguments

In Kotlin we finally have well-known optional and named function arguments. There is no longer need to create several method overloads with similar arguments. We can define function with default arguments as follows:

fun getArea(width: Int, height: Int, stroke: Int = 0) {
    …
}

and then call it like so:

getArea(10, 10)
getArea(10, 10, 2)
getArea(width = 10, height = 10, stroke = 2)

Functional programming with Lambda

Lambda has been available in Android for some time, but only if your project is using Java 8 or Retrolambda. If you cannot migrate to Java 8, Kotlin is the way to go. The language allows us to filter, map, and do the other “streamy” operations over standard collections out of the box and remove another library from the dependencies. We can easily write LINQ-style code like below:

names
    .filter { it.length == 5 }
    .sortBy { it }
    .map { it.toUpperCase() }

Extension functions

Extension functions are another example of well-known feature that is still lacking in Java. They allow us to add functionalities to existing class really easily, without the need of creating separate classes (which usually ends with “util hell” in your project) or extending existing one. Let’s try to extend String class with functionality of replacing all dots with commas in the string. In Java we would end up with something like this:

public class StringUtils {
    public static String encodeString(String str) {
        return str.replace(".", ",")
    }
}

in Kotlin we can have

fun String.replaceDots() = replace(" ", "_")

and then use it like so:

var number: String = "100.00"
number.replaceDots()

Data classes

It’s hard not to mention this little precious small feature. How many lines do you think you need to declare a class Person with three properties: name, age, and city of birth, along with copy, equals, hashCode, and toString methods? In Kotlin, just one:

data class Person(val name: String, val age: Int, val cityOfBirth: String)

The compiler automatically derives the following members from all properties declared in the primary constructor: equals(), hashCode(), toString() and copy().

And a lot more

Besides above features, there is still a lot more in the language that is worth mentioning really quickly. These are:

For the full documentation on the language and to check how it works in details I strongly recommend checking the official docs available on the Kotlin website.

Little flaws of Kotlin

Surprisingly, there is not much of them that could be easily found.

In Kotlin classes are final by default. That means that you cannot extend them unless you use modifier “open” on them. This is not standard Java behaviour and takes some time to get used to. This is explained by the JetBrains as answer for Effective.java Item 17: Design and document for inheritance or else prohibit it.

Kotlin build takes little longer in general. With all the language functionalities there is a little bit of a build time overhead. But it’s not as bad as you might think. Detailed statistics can be found in the article here. In the conclusion section, we can read:

We benchmarked a few different scenarios to see if Kotlin could keep up with Java when it comes to compilation times. While Java does beat Kotlin by 10–15% for clean builds, those are relatively rare. The much more common scenario for most developers is partial builds, where incremental compilation makes large improvements. With the Gradle daemon running and incremental compilation turned on, Kotlin compiles as fast or slightly faster than Java. If you were holding off on trying out Kotlin because of compile times, you don’t have to worry any more: Kotlin compiles as quickly as Java.

Conclusion

All in all, Kotlin is a good tool to pick up for your project. Doesn’t matter if it is an existing one or new. Interoperability with Java makes it really easy to integrate with the Java code. Learning curve is really nice. It should take no more than just a few days to make a full switch. All of the language features make development easier, faster, and more enjoyable, and I can assure you, you will appreciate switch from Java to Kotlin really quickly! : )

About the author:

Paweł Rybicki

Android developer at BT Skyrise. Enthusiast of clean MVP architecture and MVVM. Lately more into Kotlin and less into Java. Always interested in new technologies and tools which would make Android development more satisfying. Got a beautiful dog and named him Pixel before Nexus 6P was even released. Then Google followed his steps with their new flagship phones.

Next Post Previous Post

blog comments powered by Disqus