My 50 days of diving into Kotlin

Kirtan Thakkar

Kirtan Thakkar

Life is all about learning

It was May 17, 2017. I was on my desk with my laptop, to watch the live stream of Google I/O 2017. As always, I was waiting for the Google I/O Keynote, for some exciting announcements. And to my surprise, they announced official support for the language Kotlin on Android.

That thrilled my mind, literally! A new language other than Java, for Android, was really really exciting. But the name was new to me. I have read somewhere some blog posts before with Kotlin code on Android, but I didn't care at that time and ignored them as there was no official support from Google. But, the time has changed and they have the official support for Kotlin.

So, the first question was, what is going to change with Kotlin. As everything currently written, is in Java. That includes AOSP code. What about the libraries I use, everything is Java. Glide, Picasso, OkHttp, Retrofit, Firebase etc, are in Java. But that question was also answered soon. Kotlin is interoperable with Java. Everything existing written in Java can work with Kotlin. That was really a great news!

Now, the second question was, why should I code Android Apps in Kotlin, and not in Java. That was really a great question (I am praising myself because it's a great question!). Why should I learn Kotlin from scratch and not use my existing java skills? (even though I never liked Java) The thing is, Kotlin was designed to work way smarter than the Java, as it was designed from scratch considering the pain points of the Java. The language is not new, it is stable and has first-class support for Android from the day it was announced. And after I have seen this demo, I was convinced to code in Kotlin (and say no to Java, yay!)

I dived into the documentation. Learned and tested it. It worked flawlessly with my existing code. It dramatically reduced the number of lines of code compared to Java.

Here are some of the great features I have discovered while learning Kotlin.

Null-safety

You must have seen the message "Unfortunately, your app has stopped" with the button saying "OK" (but I'm not ok with it). Most of the times it is because of "NullPointerException" (yes, we all hate this). Kotlin eliminates the null references unless you explicitly tell them. This makes everyone happy.

Lambda functions

Lambda functions are anonymous functions which ease the tasks of calling functions and inlining functions. We can pass the functions as parameters to other functions and also return the functions instead of just properties. A simple example would look like this:

myList.map { val -> val * 2 } // This multiplies every value of list by 2
myList.map { it * 2 } // even shorter. Single argument can be represented with **it**

String Templates

You do this every time when you concat the strings with the variables. While logging values, showing toast, generating notifications etc. No more --- to concat. You can directly write expressions inside double quotes without explicit concatenation.

// Java
"Hello, " --- username + " !"
// Kotlin
"Hello, $username !"

This syntax is also pleasant while reading. It makes developer's life easy.

Inline functions

I discovered this feature while creating small functions which reduce the code a bit more. For example, writing a Toast requires a single line of code in Java. But, you can even simplify more with the help of Kotlin functions.

// Java
Toast.makeText(this,"my java toast",Toast.LENGTH_SHORT).show()
// Kotlin
toast("my awesome kotlin toast")

This can be done with the toast function like this

inline fun toast(message: String) {
Toast.makeText(this,message,Toast.LENGTH_SHORT).show()
}

Using this as a normal function, requires an additional method call, an additional burden for calling a function for single line execution. But, by making this function inline, it reduces that overhead. It simply replaces the toast function call with the code written inside the inline function toast at compile time. So we get what we what without an additional method call. But, keep in mind that writing large inline functions also increases the compiled code size.

Extension Functions

To say it in a simpler form, extension function is a function added to an existing class without extending it. Extension functions provide the ability to extend a class with new functionality without having to inherit from the class. For example, to toggle the visibility of the view, you do it something like this in the normal function:

if(myView.getVisibility() == View.VISIBLE)
myView.setVisibility(View.GONE);
else
myView.setVisibility(View.VISIBLE);

Instead of doing this, you can create an extension function in Kotlin and call it directly from a view instance.

fun View.toggle() {
visibility: if (visibility == View.VISIBLE) View.GONE else View.VISIBLE
}

After you declare an extension function toggle() on View with View.toggle(), you can call toggle() method directly from the view.

myView.toggle()

That's it. And the visibility of the view will be toggled. The method will work just like it is a native method of the View class. So, you don't have to inherit it to add a functionality to the existing class.

Interoperability with Java

Kotlin can work with the Java code without any issues. That is one of the biggest advantages. All the existing code written in Java can directly work in Java. So, you should not wait to get your favorite library supporting Kotlin. You can find more details about it here.

Smart Casting

In Java, for declaring variables, you start it with the type of a variable (class name). Then put the name and then assign the variables. In Kotlin, you start it with the keyword var/val, then the name of the variable, ":" and the type. But when assignment and declaration happen on the same line, you can ignore specifying a type.

var str : String: "Hello, World!" // normally
var str: "Hello, World!" // smart cast

The second line uses smart casting and evaluates the right-hand side of the expression. From the value of the right-hand side, it implicitly provides the type at the compile time. And you don't have to worry about providing type in each of your declarations.

Data Classes

Creating or maintaining model/data classes are a regular thing we do every day as a developer. Creating properties and then getter/setters, copy(), toString(), equals(), hashCode() etc. Kotlin makes our life super easy by introducing the data classes.

data class User(val name: String, val age: Int)

This single line does all these things. It generates getter/setters, toString method, hashCode/equals pair, copy functions.

Named arguments / Defaults

With the super small sized data classes, you can provide the default values. Those values will be used if you don't provide the argument while calling the function. Here, it comes another feature of Kotlin - Named arguments. Suppose you have a function which takes 10 integer arguments. When you call that function, the code used there will never give you the understanding of what is happening there.

myAwesomeFunction(5,2,1,3,5,3,0,2017,12,1)

By looking at the function, you can never predict which argument is for what. With named arguments, you can call the function like this:

myAwesomeFunction(year =2017, month =12, day =1)

If other arguments are provided the defaults, you can simply ignore it and they will get the default values. With named arguments, you can pass them in any order and it makes clear what is being passed as arguments to the function.

Anko - Kotlin library build for Android

anko is a library built by Jetbrains (people who build Kotlin) for pleasant android development. It provides so many functions which reduce your android boilerplate code dramatically. With this, you can speed up your development by focusing on business logic and not the boilerplate code.

K4Kotlin

K4Kotlin is a sweet, small set of Kotlin functions to reduce your android boilerplate code. After checking out Kotlin, I was so much excited, that I wanted to reduce my source code even more and make it more easy to maintain. So I build this library K4Kotlin. Do visit, and let me know if you have any ideas.

Also, created BackgroundManager library written in Kotlin. It was a very pleasant experience working with Kotlin in a few days. The code is now, so much easy to read and maintain.

We converted an existing completed app to Kotlin in ~20 hours

There is an official Java-to-Kotlin conversion tool available which does the job fairly good. It converts the 80% of the code error free. You may have to adjust some of your code portions to make it right. At our organization, we took up the challenge to convert an existing app fully written in Java. It took ~20 hours to convert the whole app to Kotlin with the help of conversion tool and some manual efforts to correct the code. Then you can make some extra efforts to take the advantage of Kotlin features.


It's new, it's fun. It removes almost all the pain points of Java and making coding interesting again. If you are just starting out with Android, go with Kotlin, and if you are an experienced developer, do not wait to get started with Kotlin. The efforts are worth it. #BuildBetterApps