Source: kotlinlang.org

Time to Inject Crisp N Clean Poetry in your Android Code via KOTLIN: A Detailed Overview

Since the time Kotlin became the official language of Android at Google IO 2017, there has been a risen inquisition about the very language. And some of the professional and robust Java poets of Android had the query in mind as:

Come On, Punk! What’s the big deal in Kotlin? Is it of more fun than Java? Is it sweeter than Java?

Well some among them, who earlier had a taste of Kotlin had the answer! And it’s a big YES to everything!

Before penning any further pointless discussion, let’s get to the point so that you don’t curse me for opening this link. I mean honestly, yeah! :\


What is Kotlin?

In short, Kotlin is the language which Android devs both deserved and needed! Kotlin is a statically typed programming language, which is 100% interoperable with Java (Yeah, you can have both Java and Kotlin classes in your code and use eachother’s references and methods, and things will just work. Cool, ain’t it?!). From a deeper insight, it is a perfect blende of both Object Oriented and Functional Programming with support for great features like extension functions, function lambdas and function as a type, higher order functions and many more.
Archaeologically speaking, Kotlin was officially released in February, 2016 as 1.0 and currently the version is 1.1.2 which was released in 25th April, 2017. It was coined by JetBrains, the same company which gifted us with the IntelliJ IDE.


Talking Business, Why should you really care to induce Kotlin in your perfectly shaped Android app?

At a time, when our code is plagued by uncountable NullPointerExceptions, useless yet worthy POJO classes with unavoidable getters and setters, dirty yet unavoidable assignments, ugly yet valuable Util classes, painful handling of mutability and immutability, boring and irritating semi-colons, and all the foresaid in conjunction with limited flexibility of code with abundance of boilerplate code(meaning no offense to Java patriots!!), Kotlin is the much needed vaccination.


Now, having made all the above statements, let’s have a modularized discussion on each of these.

  • Non-nullability in Kotlin: Well, a Kotlin code won’t compile if there’s a chance of a null-pointer exception happening while executing unless if you’re illusioning the compiler to believe that a statement which can be null as non-null! Let’s dig deeper by looking at the following piece of code:
Fig 1: NonNullability

Things to take note:

  • Huh! Sounds fun, right? But at the last line of the code I used something like ?: and this is called the Elvis Operator which acts as the backup mechanisms in case null occurs in execution. So, now, in our very first line of the above code’s screenshot, nullCheckIncorrect can be made to a proper error-free initialization if we use this:
val nullCheckIncorrect : String = null ?: “Not Null now”
  • Also, from the glimpse of the above code, you could notice that I did not use a single ; in my code. In Kotlin, semi-colons are purely optional. In fact, AndroidStudio will continuously bug you if you use semi-colons by throwing warnings that those are unnecessary!!
  • Another important thing that one can notice here is the manner in which variables, called as properties in Kotlin, are declared. Here, two keywords, val and var are used. val basically denotes values or rather properties which are immutable, i.e. the final of Java. And var denotes the mutable properties, the value of which can be changed. val properties can be assigned only once. Kotlin took this distinction of Mutability and Immutability to a core level and everything we declare will either be a val or a var .
  • One more thing to mention here is the type of a property. If we take the example of the above snapshot, we have the property nullCheckCorrect which we have specified will be of type nullable String by specifying the following: String? . Also, we have the property, missionNPE which the compiler inferred to be of type Int? even when we did not specify it’s type. Yup, in Kotlin, the type specification is completely optional. Type will be inferred to a property based on its first assignment.

  • Avoiding the POJO classes with too many getter setters: Quite often, we are in need of Models to do some operations like feeding the adapter of the RecyclerView with some data or some other operations and we have created a lot of them. Also, we create huge number of getters and setters for those models. In Kotlin, since we user Properties, the setters and getters are not at all required. They will automatically be called, whenever, we try to set or get values. We do everything via the Properties. A bit unclear? Let’s checkout an example from the snapshot:
Fig 2: POJO Model in Java

The above is an example of a Model in Java. Let’s see how it looks in Kotlin from the below screenshot:

Fig 3: POJO Model in Kotlin

While assigning values, we can simply do POJOModel().property2 = 10 and the respective value of the object will be equal to 20.

Note: In Kotlin, a new object is created by just calling the constructor. new operator is not there in Kotlin. Also, there is something called Data classes, which would literally make this implementation in one line, in Kotlin, will be covered soon when we cover Types of Classes.


  • Conditional Statements in Kotlin, a lot cleaner: If-else statements are the same in Kotlin as they are in Java. But the switch case in Kotlin is a lot cleaner and a powerful one. By powerful, I would like to draw a scenario. In Java, there used to be significant amount of problems when we used instanceOf operator. Well, that was a pain. Let’s look into the switch statement of Kotlin by taking something of this sort.
    So, let our problem statement be to create a function that takes an object as input and return 1 if it is of type String , 2 if it is of type Int , 3 if it is of type Float and -1 otherwise.

Let’s look into the screenshot:

Fig 4: Switch Basic

Here, is is the alternative to instanceOf and we could do it using a switch. And in Kotlin, functions are declared using the fun keyword. Any just like the Object class in Java. The return type convention and the paramter convention as that which is used in properties. So, basically, it’s fine but we aren’t excited as there’s not much Kotlin magic involved in here, right??????!!!

So, let’s see the magic :

Fig 5: Switch with a tinge of Kotlin magic

Now that looks super cool. We can use switch statements as the returning values in Kotlin!!! But if we do so, the else which is basically the default has to be implemented for sure.

What if I tell you that you could see further Kotlin trance in the above function?

Trust me, I am not stoned to say this!!! The below screenshot is a proof :P

Fig 6: Switch with high dose of Kotlin power

Now, a function can be directly assigned to a switch statement which returns a value and that in turn, becomes the return type of the function!!!

Well, this is Kotlin and this is its power!!


  • No need of findViewById(): There is something called synthetic import in Kotlin and the respective view will be imported to your Kotlin View/Activity/Fragment with the name of the id of the view. For instance, look at this:

Below is the layout file for my MainActivity :

Fig 7: Layout File of Activity

Now, look at the MainActivity Kotlin file. We can directly access textView which will point to the respective TextView with the id as textView . So, we can get rid of findViewById :)

Fig 8: Synthetic Imports

Note: You might need to add the Kotlin plugins in your gradle for the above to take effect. Consider adding these in your app’s gradle:

apply plugin: ‘kotlin-android’
apply plugin: ‘kotlin-android-extensions’

  • Interfaces can have methods with body as well as static methods: Well, in Kotlin, you can have abstract methods, methods with bodies and even Static methods. These can come to a hell lot of effectiveness. See the example below from the screenshot:
Fig 9: Interface can contain anything

Here, in Kotlin, companion object block is used to denote all the static members of the particular class or interface.


  • You can add methods to any class, including the library classes without extending them: Yes!! Here’s why I mentioned that Utils crap can be plucked off from our code. Suppose you want to add a method called visible() in the View class which will make the respective view to set it’s visibility to visible. Instead of writing a Utils method for that, we can write that method inside the View class itself. So that, our textView can just call textView.visible() to call the desired function. This is done through extension functions, which will be covered soon.

So, there’s ample of power boosters in Kotlin. And there are a lot lotttt more!

Kotlin can indeed make you a poetic coder!