Introduction to Kotlin for Android Developers

At Google I/O 2017, the Android team at Google announced Kotlin as the official language for Android development. With this update, Android developers can now enjoy the features of a more modern programming language. That said, Android developers are not forced to used Kotlin and can keep using Java which is still supported.

Why using Kotlin?

  • Interoperability: Kotlin is a JVM base language, it is fully ‘inter-operable’ with Java. This means we can have Kotlin code can co-exist with Java code and vice versa.
  • Kotlin is a programming language developed by JetBrains, same company who developed IntelliJ. Android Studio IDE is based on IntelliJ.framework.
  • Modern programming language fully supported. All the features of Java 1.8 are not available when developing using Android SDK (if need to support lower version of Android).
  • Safer: Deal with null pointer at compile time. Preventing null pointer exceptions is much easier.
  • Expressiveness: Kotlin will in many case involve writing less code for solving same problem.

Before going deeper into these new features, lets start from basic.

 

Variables

Mutable Object

In Java, we would have following code to represent a mutable object of type String

String mObject = "Hello World";

 

This would be the equivalent in Kotlin:

var mObject: String = "Hello World"
  • The “var” keyword is used for mutable type object.
  • The type of the object (String) is specified before its name (mObject) You can think of it as mObject “extends” String. (e.g, mObject: String )
  • Semi-colon is optional in Kotlin.

Inferred Type

However, we can simplify the code as Kotlin can automatically Infer type of the object. Kotlin can infer the type of the object based on the value which it is set to. For example, since we are assigning the string “Hello” to the object, we don’t need to specify its Type:


var mObject = “Hello”

If now, we instead integer value “10”,  Kotlin will infer the Type of the object as Int


var mObject = 10

 

Immutable Object

An immutable object is one whose value is set once and cannot be changed. In Java, we are used to the keyword “final” to describe an immuatable object:


final String MOBJECT = "Hello World";

The “val” keyword is used to describe a immutable in Koltin:


val contantObject = "Hello World"

The general good practice is to always use immutable as far as possible. This makes code more predictable and will be important when working with Null safety feature which we will look into the next section.

 

Null safety feature

A common crash in many programming languages (including Java) is when accessing an attribute or method of a null reference. In Java this would result in a crash equivalent of a NullPointerException (NPE).  This error is also known as The Billion Dollar Mistake.

Kotlin’s type system is designed to prevent NullPointerExceptions.


val strOptional: String? = null

strOptional?.length

This is equivalent to following in Java:


if (strOptional != null)

    strOptional.length()

strOptional?.length: If and only if the object strOptional is not null, will the length method be call

Note that the “?” is required for the code/project to compile. We can use not-null assertion operator (!!) as below to force the code to compile, however in the above scenario, it would result in a NPE.


strOptional!!.length

 

Classes

Classes in Kotlin are declared using keyword class. We will create a Class which extends Activity from Android SDK.


class MainActivity: Activity {}

This would be equivalent of following in Java:


final class MainActivity extends Activity {}

Classes are closed by default which is equivalent of “final” in Java. So we won’t be able to extend the class “MainActivity” in another class. To make the class extendable, we have to explicitly declared class as open or abstract:

open class BaseActivity: Activity {}

MainActivity can extend BaseActivity of if BaseActivity class is “open”:

class MainActivity: BaseActivity {}

 

Data classes & Properties

Kotlin provide Data type classes and Properties which avoid many boilerplate which would be required in Java which creating POJO classes. Properties are equivalent to fields in Java but which includes getters and setters. However in Kotlin, we don’t need to explicitly declare getters and setters, it will be automatically created under the hood.

Let’s say we have a User model which requires the following attributes (properties in kotlin): “firstName” and “surname

public class User {
    private String firstName;
    private String surnameName;
    private String mood;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getSurnameName() {
        return surnameName;
    }

    public void setSurnameName(String surnameName) {
        this.surnameName = surnameName;
    }

    public String getMood() {
        return mood;
    }

    public void setMood(String mood) {
        this.mood = mood;
    }
}

We can have the above class with only 1 line in Kotlin by using “data” class  contain firstName and lastName properties:

 data class User(val firstName: String, val lastName: String, val mood:String) 

Kotlin will generate the generic getters and setters methods under the hood for properties. That will allow us to write less and also make it easier to manage changes.

 

Instantiating an object

When instantiate an object in Kotlin, we don’t need to specify the “New” keyword each time as in Java:


val user = User("Frank", "Einstein", "happy")

 

Data classes come with some  handy functions:

  • copy() -> This is handy if we are using immutable objects.

A general practice is to use immutable objects when possible to avoid unexpected changes from other part of our code. e.g,


val user = User("Frank", "Einstein", "happy")

val userUpdated = user.copy(mood = "angry")

  • equals() -> compare all properties of object to another to make sure they are identical:
user.equals(userUpdated) // false since Frank's mood has changed

 

Functions

Let’s create a small function which takes two integers and return their sum in Java:


private void sum(int x, int y) {
    return x + y;
}

In Kotlin, functions are declared using the “fun” keyword. Parameters will be

fun sum(x: Int, y: Int): Int {
   return x + y
}

Note that for the parameter X or Y, we write the Name first, then its Type. The return type (Int) is at the end just before function body.

If the result can be calculated in a single expression we can omit the curly braces and simply specify the function body after “=” symbol as below:

fun sum(x: Int, y: Int): Int = return x + y

 

Higher-order function

Functions are first class citizen in Kotlin, which means function can be passed as variable, arguments or return from other functions. We will store same sum function into an object using lambda expressions as below:

val sum = { x: Int, y: Int -> x + y }
  • A lambda expression in Kotlin is surrounded by curly braces {}
  • the code before the “->” sign x: Int, y: Int  is parameter declaration for our function
  • the code after the “->” sign is the body of the function
  • the return type is automatically inferred with Kotlin as we already know the parameter is of type int, the expression will return and Int

 

Extension Function

Another interesting feature with Kotlin (and other modern programming language) is Extension function. If you are new to this concept, I will try to explain you the concept by using components from Android SDK.

Imagine you want to have a method for all your Activity classes. In Java, we would create a “BaseActivity” class which will have the required method implementations, and then have all of our activities extend that BaseActivity and inherit the method. Kotlin provides a special feature known as Extension Function. Instead of base calls, a static method will be created and made available to the existing Activity class from the Android SDK:

fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(this, message, duration).show()
}
  • Note parameter default value is used for Duration parameter: duration: Int = Toast.LENGTH_SHORT
  • “this” -> refers to the Activity itself. Inside of the Extension we will have all methods which are accessible from the Activity class. For e.g getApplicationContext().

 

That works like magic. The extension function can be written anywhere in our project. I understand Kotlin basically generates a static method which is made available to actual Activity class:

class MainActivity : Activity(), MainContract.View {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        toast("this is toast from extension function")
    }

}

Extension function is very useful if we want to add a function into a code base which we cannot modify class inside of Library and Android SDK.

The Kotlin team developed a robust library for Android which implements many useful extension functions: https://github.com/JetBrains/anko which basically “adds” new features to Android Framework. It might be worth looking into.

 

Conclusion

Kotlin is similar to Java, it runs on JVM and is fully supported by Android Studio. I would say it’s a must for Android developers to give it a try. There are indeed many new features some which I covered in this blog post. I hope this is helps you started to get into Kotlin language. In future blog posts, I may go deeper inside specific features which I find useful. You can always  keep in touch by clicking on “Follow” button at the bottom right corner. Stay blessed. Cheers

Please Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s