/ KOTLIN, ANDROID

Kotlin - What's So Cool

Kotlin is a programming language for the Java Virtual Machine (JVM) and can, therefore, be used anywhere Java is used today (which is virtually anywhere). This includes server, client, web, and Android development. It’s developed by JetBrains who are currently working to bring Kotlin to embedded systems and iOS as well, potentially making it a one-stop language for all application areas.

Recently I have been using it while working on one of my android app and since I have also used Java for android, I am able to it with Java and just fell in love with its features and the ease it provides to the developers.

It is in the industry since 2011 but gain popularity in 2017 when Google announced it to be the next official android programming language at I/O’17. Since then it is expanding with a much faster speed. In nearly one year 33% of the android apps have shifted their base to Kotlin and companies like Linkedin and Pininterest have their apps running on it. It is a really useful skill for android developers both in the learning as well as job perspective.

Let’s see what makes it better than java.

Support

Our daily IDE Android Studio supports Kotlin through an external plugin (for version older than 3.0) and as an inbulit support after version 3.0 of Android Studio. Android Studio can understand, compile and run Kotlin code just as it does for Java.

Not just Android Studio choose any Java IDE it will support Kotlin plugin.

Expressiveness

With Kotlin, it’s much easier to avoid boilerplate code because the most common patterns are covered by default in the language.

For instance, in Java, if we want to create a data class, we’ll need to write (or at least generate) this code:

public class Artist {
 private long id;
 private String name;
 private String url;
 private String mbid;
 public long getId() {
 return id;
 }

 public void setId(long id) {
 this.id = id;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public String getUrl() {
 return url;
 }
 public void setUrl(String url) {
 this.url = url;
 }
 public String getMbid() {
 return mbid;
 }
 public void setMbid(String mbid) {
 this.mbid = mbid;
 }
 @Override public String toString() {
 return “Artist{“ +
 “id=” + id +
 “, name=’” + name + ‘\’’ +
 “, url=’” + url + ‘\’’ +
 “, mbid=’” + mbid + ‘\’’ +
 ‘}’;
 }
 }
 

With Kotlin, you just need to make use of a data class and it is done:

 data class Artist(var id: Long, var name: String,var url: String,var mbid: String)
 

This data class auto-generates all the fields and property accessors, as well as some useful methods such as toString(). You also get equals() and hashCode() for free, which are very verbose and can be dangerous if they are incorrectly implemented.

You can also make custom constructors. For more on classes and functions refer to this blog.

Performance

As we just saw how Kotlin saves us from writing long coding files and reduces code size to much extent but what is the cost for this?. Is it slower than Java just like any other high level language like python written over a low level language?

Well the answer is no, there is no performance lag between Kotlin and Java because the complier interprets the Kotlin code as Java code and then performs the action. Hence it is making it easier to write lesser code and that too with no performance issue. Isn’t this cool?

Interoperability

You can continue using most libraries and code written in Java, because the interoperability between both languages is excellent. It’s even possible to create mixed projects, with both Kotlin and Java files coexisting. Hence there is no problem if you want to use any andoid library written in Java, it will work the same.

Null Safety

When we use Java, a big amount of our code is defensive. We need to check once and another whether something is null before using it if we don’t want to find unexpected NullPointerException. Kotlin, as many other modern languages, is null safe because the type explicitly defines whether an object can be null by using the safe call operator (written ?).

We can do things like this:

 // This won’t compile. Artist can’t be null
 var notNullArtist: Artist = null

 // Artist can be null
 var artist: Artist? = null
 // Won’t compile, artist could be null and we need to deal with that
 artist.print()
 // Will print only if artist != null
 artist?.print()
 // Smart cast. We don’t need to use safe call operator if we previously
 // checked nullity
 if (artist != null) {
 artist.print()
 }
 // Only use it when we are sure it’s not null. Will throw an exception otherwise.
 artist!!.print()
 // Use Elvis operator to give an alternative in case the object is null.
 val name = artist?.name ?: “empty”
 

Extension functions

You can add new functions to any class. It’s a much more readable substitute to the usual utility classes we all have in our projects. You could, for instance, add a new method to fragments to show a toast:

 fun Fragment.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(getActivity(), message, duration).show()
 }
 

And then use it like this:

 fragment.toast(“Hello world!”)
 

Not just functions but properties of classes can also be extended.

Casting

Casting in done by using an as keyword:

 val x: String = y as String

This is considered “Unsafe” casting, as it will throw ClassCastException if the cast is not possible, as Java does. There is a “Safe” cast operator that returns the null value instead of throwing an exception:

 val x: String = y as? String

For more details on casting, check the Type Casts and Casts section of the official documentation

Lazy Loading

The lazy-loading feature basically increases the startup time, which is very useful when using Kotlin for Android app development. In simple words, it’s the best solution for all developers who wants to reduce their Android app startup time so that their apps’ content can be shown faster.

With lazy-loading feature, Android developers can load the only resources into main memory which are necessary. For example, if you’ve a shopping app, majority of users will only browse your selection, that means you could have the payment API be lazy loaded.

Collection Filtering

We all know that when working with an API, we developers need to deal with collections quite often. But by using Kotlin’s collection filtering feature, it’s easier to tell what your resulting list should contain. In fact, filtering a collection using the built-in Kotlin is very comparable to other programming languages such as Swift collection types or Java 8 streams.

Bye Bye FindViewByID (Static Layout Import)

Gone are those days when we need to get reference of a view by its ID if we want to perform any action on that view in Activites and Fragments. Now Kotlin allows you to import all references to views from the layout with one import.

For example look at the XML layout below:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="co.ikust.kotlintest.MainActivity">

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</RelativeLayout>

And the accompanying activity code:

package co.ikust.kotlintest

import android.support.v7.app.AppCompatActivity
import android.os.Bundle

import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        message.text = "Hello World!"
    }
}

What, we can use the view directly using its ID, well yes with just one import shown below we can access all the views in that XML file.

 import kotlinx.android.synthetic.main.activity_main.*

Functional support (Lambdas)

What if, instead of having to declare an anonymous class every time we need to implement a click listener, we could just define what we want to do? We can indeed.

As an example, let’s show how to implement click listener in Java and Kotlin.

In Java:

view.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(v.getContext(), "Clicked on view", Toast.LENGTH_SHORT).show();
    }
};

In Kotlin:

`view.setOnClickListener({ view -> toast(“Click”) }) This is only a small selection of what Kotlin can do to simplify your code and make our life easier. If you are trying to get into android surely try a hand on Kotlin once.

Comment below if something needs to be corrected.

References:

  1. Book - Kotlin for android developers by Antonio Levia
  2. Ten Kotlin Features To Boost Android Development