Java has been the main programming language for Android development since its introduction to the development world. But after some years, the community has been asking for a more modern, concise, productive, and boilerplate less alternative to do more with less effort. And Kotlin shows up! During the Google I/O 2017 keynote, Google promoted it as the official programming language for Android development, increasing the language adoption and migration of existing Android apps. This post will help you in moving from Java to Kotlin.
Since the origin of Kotlin in the year 2015 it was buzzing as something interesting in the market but got a straight boom as soon as Google declared Kotlin as the official language for Android development in the year 2017.
( Maybe due to the copyright case going b/w Google and Oracle.)
With this, developers started dirtying their hands with Kotlin and realized that It does exactly what it is made for. ie; Saving the pain of developers by solving the challenges that java gives them beforehand.
Kotlin is also a JVM language and is completely interoperable with Java. The goal of creating Kotlin was to make a tool that can work with Java in parallel and also an alternative to Java.
Because of its neat code, features, and developer friendliness, it is holding a high position in the most loved and wanted programming language survey of StackOverflow 2018, 2019, 2020.
Here, I will iterate through the features that it provides and the reasons why it is worth migrating to Kotlin especially for Android application development.
Null Safety — Untroublesome Null Pointer Exception
Tony Hoare’s billion-dollar mistake — Null reference
The old, verbose Java is in a strong relationship with Null Reference also known as the billion-dollar mistake. As soon as it gets some null reference, it throws NullPointerException causing the system to crash.
Java gives no null safety checks for declared types. Either put the block of code in try{}catch() and handle the thrown exception or check if(XYZ!=null){} and then proceed as desired. This led to a lot of boilerplate code.
Here Kotlin comes with a null safety feature that aims to eliminate the NPE from the code. It has 2 types of references, one can hold null and the other cannot. A variable is allowed to hold null reference just by declaring it as nullable type i.e; append a ? with the type.
Now, due to its nullable type, Kotlin is also prone to NPE, but it offers several properties to deal safely with the null reference. these are listed as below:
- Safe call operator- “ ?.”
- Elvis operator- “ ?:”
- Converting to safe casts- “as?”
- let(), also() & run() scoping functions
Despite null safety, there are several conditions in which it throws an NPE-
- An explicit call to throw NullPointerException()
- Usage of the “!!” operator
- leaking this
- and sometimes while interoperating with java.
Cleanliness is next to Godliness
Kotlin helps you write neat and concise code. If you compare a Java class with that of the Kotlin class you will figure out that you need to write less code to achieve the same operation. This significantly reduces the amount of boilerplate code and eventually decreases the class size.
Below are the features that let you write less-
- No need for findViewById(). Use the ids in the XML directly in your activity and fragments.
- Data Classes
- Object expression instead of a singleton class.
- Optional parameters for methods
- Lambda support
- Smart casts
- Powerful when instead of switch
- String templates
Mutable and immutable variables
Mutability is the core concept in Kotlin. The mutable ones are those whose value can be manipulated at any time. whereas, the Immutable ones are those that are final in terms of java i.e; once assigned, their values can’t be changed in the future.
For the variable, we have var for the mutable ones and Val for the immutable ones.
Talking about the collections, then we have the immutable list and if we want to manipulate the data further then we need the MutableList object.
Refined Collection framework
Kotlin turned the whole traditional java collection framework. Kotlin Collection API has a Collection interface that supports read-only methods. Whereas, the MutableCollection supports both the read/write methods.
we can create a simple list by using the list of() method and a mutable list by using a mutable list of(). The same goes for ArrayList, Map & Sets.
Now we have several methods that make life much easier.
- list.slice()- Obtain a sublist from a list
- list.filterNotNull()- returns a list after removing all the nulls
- list.filter{predicate}- returns a filtered list based on the condition provided in the lambda
- list.map{it.someField} & list.flatMap{it.someField}- returns a new list* of someField.
- list.drop(n)- drops the first n elements from the list.
- list.dropWhile{condition}- drops the first few items based on the provider condition.
Apart from these, there are furthermore methods that the Kotlin framework provides. I usually use the above one the most.
Powerful Extension Functions
Now let’s talk about the extension function that is a completely new feature added to Kotlin.
Let’s suppose you need to add a method xyz() to your Activity or a predefined class. Then you have 2 options.
1- Either you extend the activity to your BaseActivity() and define the method there. Then extend each of your activities all over the app with the BaseActivity and use the xyz().
2-There are several classes that are final by nature and can’t be extended e.g- String. In this case, you create a util class and define the method there. Then call the method using the Util class.
Here comes the concept of Extension function where you may eliminate the need of extending the classes or making utility methods. You can directly make a function to the class (no matter if it’s final or not) and then can use the method anywhere in the scope of the class.
For example- I have an EditText that takes a mobile number as input. After the input, you need to validate whether the number is valid or not. So, if we have a util function it looks like this.
object Utility{
fun isValid(mobNumber:String):Boolean{//check validity
return true/false
}
}
Now the procedure to call this method is
Utility.isValid(editText.getText().toString())
Let us now create an extension function for the EditText class. The extension function looks like this
fun EditText.isValid():Boolean{
val mobNumber = this.getText().getString
//check validity
return true/false
}
and then call it directly with the object of your EditText.
editText.isValid()
Does it now look neat and clean? This is the power of the extension function that you can make any function for any class.
I think now you are fairly and squarely convinced to migrate to Kotlin. But still, as an app development organization, you must ensure some prerequisite, like this:
Is your team already prepared to move to Kotlin?
Learning a new technology or programming language requires some learning curve. So this is also with Kotlin. Some language features are completely new to Android developers and will need to be mastered, like Smart casts, Null safety, Extension functions, Lambdas, Delegations, and so on. You also can face some resistance regarding Kotlin’s adoption inside your team members.
Now it is time to give it a try
Kotlin can help make your life as an Android developer a lot easier. While developers sometimes go overboard when using cutting-edge technologies that aren’t battle-hardened, new tools do get developers fired up to build awesome things. And with six years of development, Kotlin is on pretty solid footing.
A road to summary
I would like to add the Coroutines to this list, but still, RXJava is way better than the coroutines. But when comparing it with the use of Java for Android development, it is much more convenient to use Kotlin. Putting a fact through my experience, “After using Kotlin for the past 2 years, I suggest that dear Android developers now it’s time to migrate to Kotlin. Once you start coding Kotlin you’ll love it and then will always prefer writing in Kotlin instead of Java.”