Kotlin on Android – Overview and Introduction Tutorial

Kotlin on Android – What is it?

Kotlin has kept ringing for sometime now and people are already hyping a lot about it. Ever since Android hit the world of smartphone it has proved to be very very versatile. However, it is at its core Java and seeing how Java 8 and issues which were later solved in Java 9 and Java 10. The problem is at its core lot of legacy codes written on top over and over again.

This limits the ability of Android to shift to a language that is modern and can solve lot of problems faster and better. This gave rise to the language called Kotlin. JetBrains, known for IntelliJ IDEA (Android Studio is based on IntelliJ IDEA), introduced the Kotlin language in 2011. It reached 1.0 status early in 2016.

Since it’s introduction in the market, there are a lot of cool things that can be done with the language if you are using Android Studio.

And as a icing on the cake, Google announced that Kotlin would forever more be supported as a first class programming language for Android. This has got to mean something, this has to mean shifting towards a more interoperable language like Kotlin.

In this tutorial, we will see what Kotlin can do. Create a sample class and see for ourselves our First ever Kotlin Application!!

Kotlin – What can it do?

For starters, Kotlin is highly operable, which mean you can make a api call to a Java method from the Kotlin and vice versa as well. This gives the flexibility to not be heavily dependant on a Java code alone when the top level can be your Kotlin class.

Kotlin improves further by adding some of the following features to its kitty. They are,

  1. Concise to reduce the amount of boilerplate code you need to write.
  2. Expressive to make your code more readable and understandable.
  3. Safe to avoid entire classes of errors such as null pointer exceptions.
  4. Versatile for building server-side applications, Android apps or frontend code running in the browser.
  5. Interoperable to leverage existing frameworks and libraries of the JVM with 100 percent Java interoperability.

In the following sections, we will extensively create our first Kotlin Project. Write a Class and build an Application.

Getting Started

Step 1 : Start by creating a Kotlin Project
Android Studio Kotlin Example
Android Studio Kotlin Example

Be sure to include the Kotlin Support while creating the project

Step 2 Create a Simple Kotlin Class:

Once you have created the project it is time to create our first class.

On the left side where the project is listed, you see a list of project folders. Right Click on the application name you gave>Choose Kotlin Class

Kotlin Create Class
Kotlin Create Class

Create the Class like below.

Choose Class in Find
Choose Class in Kind

Choose Class in the Kind field.

Step 3 : Create our First Kotlin Class

If you see the syntax for the Kotlin class, it starts with the class tag just like Java. But since it is statically typed, there are some change in syntax in lot of places.

If you wanted to extend a class, we simply use the : ClassName. Try this with the AppCompatActivity.

Hit option+Space for autocomplete and the relevant import statements are imported. Once done, your Class looks like this.

package com.monks.android.kotlinapplication
import android.os.Bundle
import android.support.v7.app.AppCompatActivity

class SampleActivityKotlin : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }
}

The syntax is a bit quirky to get used to, but worth the practice.

Step 3 : Create Your Layout like a normal Android Layout

Create a simple layout file with a LinearLayout and a TextView just like below.

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Sample Kotlin Activity"
        android:layout_gravity="center"
        android:textSize="30dp"
        android:textColor="@color/colorAccent"/>

</LinearLayout>

Add your SampleActivityKotlin.kt like below.

package com.monks.android.kotlinapplication

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

class SampleActivityKotlin : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.content_main)
    }
}

Our Final Output is as below.

Kotlin Sample Application Output
Kotlin Sample Application Output

Really Cool features in Kotlin

Kotlin has got really important features that are very useful for the current generation of programming.

Null Safety

One of the leading points of frustration with most programming languages, including Java, is accessing a member of a null reference. A null reference occurs when you declare an object variable but haven’t given it a value. When the program runs and tries to access that variable it doesn’t know where to look for it memory because it doesn’t exist.

If you want to allow a Null to be assigned to an object you have to provide an operator along with the object.

Assign Non-Null types

This feature is provided using a simple ?. Look at the example below.

private var SomeClass: variable? = null
Safe Call

Want to check if a variable is Null? Do not worry, use the ?. operator. This will provide a safety check on the object and wont allow null objects to call a method.

variable?.function()
The !! Operator

The dereferencing operator, forces a nullable object to be non-null. This can be a cause for NullPointerException if you force the compiler to thinking that the object neednt be checked for Null Value. Use this with care!

Sample code

variable1 = Class.method(someValue!!)
The Elvis Operator

Similar to a ternary operator, but performs a cool process. Take a look at the below example!

val someVariable = object?.length ?: 0

In the above example. the object.length value is assigned to someVariable only if the object variable is not null, else the value to the right is taken.

This is a pretty important operator, reducing the lines of code to perform null checks and then assigning a value if it is.

The most Cool Feature

How about convert your Java class to a Kotlin Class in one button press. Well, you definitely can do that!!

Choose your Java class> And open Code menu from top

Code to convert Java to Kotlin
Code to convert Java to Kotlin

Once done, here is my KotlinClass. I converted the class from the tutorial here for alertDialog.

class alertdialog : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.layout_file)

        val button = findViewById(R.id.buttonpress) as Button
        button.setOnClickListener { v ->
            val alertDialogBuilder = AlertDialog.Builder(v.context)
            alertDialogBuilder.setTitle("Sample AlertDialog")
            alertDialogBuilder.setMessage("Body of the alert dialog")
            alertDialogBuilder.setPositiveButton("Yes") { dialog, which -> }
            alertDialogBuilder.setNegativeButton("No") { dialog, which -> }
            val alertDialog = alertDialogBuilder.create()
            alertDialog.show()
        }
    }
}

Simple, concise and pretty COOOLL!!

Conclusion

Personally, it is really cool to know a new language support for Android Application. It has been long due and the major reason has been because, Google is looking to bring a new Language into the spectrum. Check the article Is Android Dead, What is Google thinking? to know more about the need for a newer language.

Just like any other language, the change is going to be a pretty time taking, but with Kotlin it is very easily interoperable with Java. Switch now, start from today. Happy coding!!

“Learn and Be Curious”

 

Leave a Comment