I was sitting in the Shoreline Amphitheater audience during Google I/O 2017 Developer Keynote when Stephanie Saad Cuthbertson announced that Google now supports Kotlin in Android Development. I was not the one who cheered aloud about that. I felt that it might not be the best idea to learn new language now even though it is a normal step in software developer career. My thoughts were like “but Java is a great, more and more flexible and so versatile language”, “it is kind of a fundamental language, the entry point to commercial development”, “so many job offers in Java out there”.
But, as for an Android developer that was not the best attitude.
When I switched to Kotlin I realized that the ability of pouring your thoughts right into Kotlin code is better than the need of ‘thinking in Java’. It is because Kotlin is more productive, mature high-level language with fantastic mechanisms and improvements that I think every Android developer should at least try. Here’s why.
In Java we often create model classes which main purpose is to hold data and provide access to it. Inside such class we declare what fields the class have, create constructors, generate getters, setters, hashCode() and equals() functions. Kotlin embraces the same functionality for classes by providing data keyword. It basically has the same purpose as the Java model class, but the number of lines needed to achieve it is incomparably lower. To note that check the below example of Product class written in both languages.
Code in Java
Code in Kotlin
Of course, you can generate all those methods in Java with one click if you use InteliJ IDE and also you might say that Java class is more explanatory. It might be true but as Kotlin is a high-level language it gets rid of boilerplate code by definition.
However, you might notice that with data class there is not possibility to use parameterless constructor in Kotlin. No worries, it is possible. To do that you just need to declare default values for fields. Just like that:
Still, it might not be the definite argument for you to transfer to Kotlin, so let me show you another nice feature.
Default arguments in methods
Imagine that you have a method that is used all around the project and you overload it to manipulate data with use of different set of parameters. And now you need to add new parameter to the method that is used widely across the whole project.
In Java you would have to overload the method with another version which takes new parameter into account and update all remaining overloads to initiate the new parameter with some default value. That might become problematic especially when we think about maintenance of the code and freedom to extend the functionality in future.
Below you can find an example of overloaded method createNickname(…).
Kotlin allows you to declare default arguments which makes overloading unnecessary. Also, it solves the problem with widely used method which in my opinion is even more important as it increases the flexibility of your code. You just add the new parameter to method definition and provide the default value there.
Then you are free to use it in your very specific place in code. Just like this:
You may have a feeling that Kotlin mechanisms understand the need and provide flexible functionality to it. Working with this language can be even more intuitive and fast. Let me bring another feature here.
Whenever you write a code that might be reusable you should consider creating extension function for the object to which the code relates. As an example, let me take a simple but frequently used mechanism of changing the visibility of a View in Android. In Java we often create those XUtils classes where we create static methods to convert, calculate or as mentioned above show or hide. We would need to pass the View as a parameter and then change visibility. Using those classes for that purpose is not the best choice. In Kotlin we have extension functions which allow to extend any generic object.
So, to write a one-liner to change visibility of any View object in Java you will write something like this:
In Kotlin, the extension function holding such functionality could be composed as below (written in separate View.kt file):
Having this extension, we can use visibleOrGone(..) on any object that inherits from View class. Now Java implementation can be rewritten to Kotlin code just like this:
I hope that since now in your Android project you will make sure that you have extensions package created, store all your extension functions over there and use them anywhere you need.
This feature was Kotlin’s benchmark when I first heard about that language. Now when I use it on a daily basis the infamous NullPointerException is just a memory of the past.
Let me compare few null safety cases in Java and Kotlin below.
Java 8 introduced the Optional which might be the alternative for nullable types. However, Optional works as a wrapper for the actual value. In comparison, in Kotlin there is no additional wrapper object created. Moreover, nullable types are respected at compile-time so any non-null-safe action will trigger compile exception. Whereas using Optional may pass the compilation without exceptions but then can trigger some error during runtime which is definitely more distracting for the end user.
Standard (Scope) Functions
Kotlin provides standard functions set which can be used against any object. Their main purpose is to execute block of actions knowing the context of the object. Inside a scope function there is a lambda expression which along with the block of action create the temporary scope of the object. Inside the block you can access all parameters that belong to the object without calling the name of the object.
Here is the template method:
Below you can find a table that shows the usage of all five functions in relation to the example template method.
|Scope function||Received (this)||Argument (it)||Result|
In one sentence, the purpose of those functions (run, let, with, apply and also) is the same: to execute a block of code on an object. Detailed article about differences between those methods could be covered in a separate article so for now let’s just use the above method and table to have an overall look on how to use them.
approaches concurrency in a very flexible way providing a light-weight threads
called coroutines. This is a vast topic to be covered in a separate article.
Follow our blog for more information on this topic.
Still, if you are an Android developer you might already know that Google started updating their libraries to be interoperable with Kotlin Coroutines (checkout newest version of Lifecycle 2.2.0-alpha01).
In Kotlin semicolons are not mandatory. This is not a functional update but let’s be clear here. A programming language which forces developer to remember about such prosaic thing seems to be a bit archaic.
Kotlin is easy to learn if you are already familiar with Java. You can find different ways of how to tackle this language on the official Kotlin site: https://kotlinlang.org/docs/tutorials/
Also, when you start working with Kotlin, Java will remain in your head as a reference language. InteliJ knows that, so there is a Kotlin bytecode module provided in their tools where you can see the bytecode of a particular class and decompile it to Java.
Moreover, if you use Android Studio the transition from Java to Kotlin can be easily achieved with help of built in converter, just copy paste your Java code to .kt class and IDE will make a basic conversion for you.
There are loads of other features in Kotlin language which when summed up make the coding easier and faster. Still Java is widely used on backend and surely it will remain usable as new version of it are being released and there are many happy developers out the. However, technology goes becoming more available and so the programming. One may say that in future we will be able to code just with voice. Who knows, but for now I think it is a good moment to take a while to have an afterthought regarding the tools that you use as a developer. From my perspective Android development is much easier and faster with use of Kotlin. I think the same feeling have Google developers as during this year I/O Kotlin was announced to be the first supported language for Android development. Still, Java and C++ remain on their places getting updates, but I consider this decision as an outline of the future domination of Kotlin.