Education

What is Kotlin and why should you care?

Written by Shaoor Munir ·  5 min read >

If you have been anywhere near Android application development in the last six months, you might have heard something about Kotlin. If you are like me, you might have stumbled over the announcement by Google making Kotlin as one of the official languages for Android development, considered it for a second, closed the browser window and would have returned to the old, trustworthy Java in all its nullable glory. But Kotlin has been gaining a lot of traction lately, with most surveys putting it into top 10 most used languages in 2017. One key factor in its popularity is its ever-increasing adaption by Android application developers.

So what is Kotlin? And should you think about switching to it after years of development in good old Java?

What is Kotlin?

Kotlin was originally developed by a team of JetBrains programmers, the same people who brought you IntelliJ IDEA (the IDE that Android Studio is based upon), PyCharm, and a huge suite of pretty cool IDEs. Kotlin is designed to be interoperable with Java code, meaning that although the syntax is completely different, the code ultimately compiles to a format which can be run on a JVM (Java Virtual Machine). This means that using Kotlin in an existing Java project is much easier than say using C++ or C# with Java. You can call a Java routine easily using Kotlin and vice versa.

So… What’s the difference?

Although the underlying idea is same and both languages compile to a similar VM code, the syntax looks a bit different. More different than C++ or C# as compared to Java. For example, look at this snippet of code written in Java which prints Hello World on the console:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }

}

Pretty simple and familiar, no? Now take a look at the same code in Kotlin:

fun main(args : Array<String>) {
    println("Hello, World!")
}

Much simpler and more compact. That’s the whole theme of Kotlin. Do the same thing, but in fewer lines and with much less nonsense. That was just a small example of how things are done differently in Kotlin as compared to Java. That should be enough to peak your interest, but now that I have your attention, let’s take a look some major structural and syntactical changes in Kotlin.

Class functionality extension

It is not entirely a new concept for some other programming languages, but it definitely is for Java developers. Kotlin allows you to extend the functionality of an existing class easily. Suppose that you want to add a function to the String class that counts the occurrences of character a in a string and return its count (seems pretty pointless, but for the sake of this example just suppose that it’s gonna save you a ton of time). You can do this easily in Kotlin by this simple snippet of code:

fun String.countOccurrences(): Int{
    //count the occurrences of character a and return it
}

You can then simply call this function from any variable of the extended class String using the regular dot notation.

var myString: String = "aabbcc"
var count: Int = myString.countOccurrences()

Null-safe by default

Remember the NullPointerExceptions that you used to get about 20 times while compiling and running the Java code? Those fun little exceptions are one of the main reasons for suicide among Android developers (I am just assuming, don’t really quote me on this). Kotlin aims to solve this problem by dividing the variables into nullable and non-nullable types. All the variable defined in Kotlin are non-nullable by default. So if you forget to assign a value to some variable and then referenced it later Kotlin code would simply not compile. Doing something like the code given below is not only frowned upon in Kotlin community, it is downright impossible to do while using a Kotlin compiler:

val name: String = null

So instead of getting an ambiguous error while you are trying to run your shiny application somewhere on your test device, it throws an error during compilation. If you really really want to assign a null value to some variable, it is, of course, possible in Kotlin, BUT not without proper checks. Kotlin forces developers to use a ? symbol while assigning and accessing a nullable variable. Consider this example where a nullable object of type Person is being assigned a null value:

val person: Person? = null
...
person?.name = "Ahmed"

Using ? character works as a proper check-in Kotlin, so if person is null, it will not try to access any underlying properties and ultimately not crash as a result of NullPointerException. The above code can be roughly translated to following code in Java (not an exact approximation, but it kind of works in a similar manner):

Person person = null;
...
if (person != null)
    person.name = "Ahmed";

Instead of forcing developers to add a check on each nullable variable, Kotlin does this automatically. Thus making the lives of millions of developers much easier.

Easier view-binding

Finding views and changing their properties is always a tedious task in Android development. Suppose that you have a simple text view with the id myTextView, this is how you will set any text in that text view using Java:

TextView textView = (TextView) findViewById(R.id.myTextView); 

textView.setText("Hello World");

Doing this again and again throughout the code becomes a little annoying sometimes. Kotlin approaches the above task in a slightly different manner. You start by importing the required views from a simple import statement:

import kotlin.android.example.main.activity_main.myTextView

After that you can simply change or use any value from the view in a similar way to how you usually handle objects, just by using the ID of the view:

myTextView.setText("Hello World")

No need for getter and setters, finally!

If you are making a class in Java which is mostly used for storing data, then it is possible that you may have to make getters (functions returning the value of a variable) and setters (functions assigning some value to a variable) for all the different variables in the class. This. Gets. Exhausting. Kotlin takes care of that by using data classes distinction. If you include the keyword data while defining a class, Kotlin makes all the getters and setters automatically, saving you the laborious task of writing out all the repetitive code yourself.

data class Person(var name: String, var age: Int, var address: String)

Smart casts

Unlike Java, which requires the developer to scream the datatype of a variable before using it, Kotlin can determine the type of a variable at runtime and perform specific actions related to each data type. Kotlin provides a very useful is operator for this purpose which can be used to check if the variable belongs to a certain datatype.

if (obj is String) {
    print(obj.length)
}
if (obj !is String) {
    print("Not a String")
}
else {
    print(obj.length)
}

You can also do some pretty cool stuff using a combination of is operator with the when-expressions capability of Kotline language. Consider this example in which a different operation is performed for different datatypes of a single variable:

when (obj) {
    is Int -> print(obj + 1)
    is String -> print(obj.length + 1)
    is IntArray -> print(obj.sum())
}

Pretty cool, right?

There are a number of other differences among Java and Kotlin, a complete detail of which is available on Kotlin community site.

Not everything is perfect

As is the case with nearly everything in this flawed and imperfect world, Kotlin has some issues too. Exception handling is not as refined in Kotlin as it is in Java. Also, Kotlin adds a bit of overhead in converting the code to a Java Virtual Machine readable code. The resulting programs in Kotlin are a bit larger in size and take some fraction of time longer than similar Java codes.

There is also a learning curve with the newer syntax that might put off some experienced Java developers. Plus due to it being a relatively new language, the online Kotlin community is much smaller than Java. This means that if you are stuck on some issue, there are fewer chances of them getting resolved as compared to more established languages like Java.

So Kotlin, yay or nay?

The question remains, should you be using Kotlin as a primary language for Android development? A large number of developers are indeed moving towards Kotlin for Android development, but it does not mean that Java will soon be deprecated. It is still the most popular programming language when it comes to Android application development. However, there’s nothing wrong with getting your hands dirty with Kotlin. Add to it the fact that Kotlin and Java can exist peacefully in a single project, so adding a couple of Kotlin activities in your Android project would probably be the best way to start testing the language. And if you like writing code in Kotlin, maybe you can someday try an all Kotlin project too.

Written by Shaoor Munir
I am passionate about technology, hardware and the future of both of them together. Email: shaoor@techjuice.pk Profile