What is Kotlin and how does it matter to Java and Android developers?

Author: Shazin Sadakath


 

If you have been doing Android application development or using IDEA Intellij Idea in the last six months, you would have heard something about Kotlin. If not Google's announcement of making Kotlin as one of the official languages for Android development must have sounded an alarm on your head to start learning about Kotlin. Ever since it was announced Kotlin has been gaining a lot of traction, with many surveys putting it into top 10 most used languages in 2017. One key factor for its popularity is its rapid growing Android application developers.

What is Kotlin?

Kotlin was originally developed by a team of JetBrains programmers, the same programmers who develop IntelliJ IDEA (the IDE that Android Studio is based upon), PyCharm, etc. Kotlin is designed to be interoperable with Java code, meaning eventually the Kotlin code will be compiled into byte code that JVM understands. This enables to use Kotlin in existing Java projects much easily and a Kotlin can be called from Java code and vice versa.

What’s the difference?

Eventhough Kotlin code compiles into byte code eventually, the syntax for Kotlin is much more concise and compact than C#, C++. For example if we have a look at Java code below;

public class HelloWorld {

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

}

The same code above in Java can be written in Kotlin as bellow;

fun main(args : Array) {
    println("Hello, Techtalks!")
}

The theme of Kotlin is about doing the same things that Java code does with much simpler and compact lines of code.

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 animal: Animal? = null
...
animal?.name = "Duck"

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):

Animal animal = null;
...
if (animal != null)
    animal.name = "Duck";

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.

Class functionality extension

It is not a new concept for some other programming languages, but it is for Java developers. Kotlin allows you to extend the functionality of an existing class easily. Suppose you want to know the no of occurrences of letter 'a' in :

fun String.countOccurrencesOf(Char c): Int{
    //count the occurrences of character submit with parameter c 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.countOccurrencesOf('c')

Easier view-binding

Android requires a lot of boilerplate code to get a view object as shown below in the code;

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

textView.setText("Hello World");

This is repetive and tedious task. 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 Techtalks")

No need of Getters and Setters

Kotlin has a data definition which will generate necessary getters and setters for a give class based on its properties. 

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

Smart casting

Kotlin is dynamically typed, as opposed to Java which is statically typed so Kotlin can identify the data type of a variable at runtime easily.

if (obj is String) {
    print(obj.length / 2)
}
if (obj !is String) {
    print("This is not a String")
}
else {
    print(obj.length)
}

You can combine if and when-expression to execute statements based on the data type of the an object.

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

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

 



Tags: Kotlin Java Android Development
Views: 656
Register for more exciting articles

Comments

Please login or register to post a comment.


There are currently no comments.