Google I/O: Kotlin for Android will Simplify User Experience Development

At Google I/O 17 this week, Google unveiled one of the most important Android developer announcements in recent years. There is now an official alternative to Java for Android app development, and that alternative is called Kotlin.

TokBox powers live video experiences within Android applications and we are pleased for this new choice that will make it easier and safer to produce compelling real-time experiences for customers. So in this blog we explore the benefits of Kotlin for app developers, and how Kotlin can be used with the OpenTok Android SDK.

Unlike Apple with Swift, Kotlin is not a new language nor it is developed by Google. Kotlin was created 6 years ago in 2011, and then officially released in 2016, by Jetbrains – the same guys that created IntelliJ Studio IDE that powers Android Studio IDE.

Here was the announcement at Google I/O:

The Kotlin Programming Language

Kotlin belongs to the set of languages that runs in the JVM (Java Virtual Machine) like Java itself, Scala, Clojure and Groovy. Therefore the language is completely interoperable with Java. This means that you can call and be called by any library created in Java, including the whole Android SDK, and our OpenTok Android SDK for Live Video applications.

In fact, it has been perfectly possible to develop a complete Android application using Kotlin, or mixing and matching Kotlin and Java, for the past two years. Becoming an officially-supported language by Google brings Kotlin to the top level with guaranteed long-term integration and enhancements.  Since we are software development enthusiasts at TokBox, we have developed several prototypes of Android apps made 100% in Kotlin using our OpenTok Android SDK over the past year.

Looking at the language, Kotlin has all the features of the modern languages that we love. It has optional typing, functions as first-class citizens (including inline lambda declarations), coroutines,  instance properties, data classes, built-in string formatting, and immutable references. Moreover, the Jetbrains team has been working hard to make Kotlin even better for Android development by adding the Kotlin Android Extensions.

In this blogpost we will take a deep dive into some of the key features of the language, its integration with Android and about using Kotlin with the OpenTok Android SDK.

No more null checking with Kotlin

One of the most beloved features of Swift is optional typing. Kotlin added it first. If you are a Java developer probably you probably can’t count how many times you have written something like `if (foo != null) { foo.bar(); }`. This can be worse, you could forget to add the if and then you could get the infamous NullPointerException. In Kotlin you have optional types, that means that you don’t really need to check for null, you just can write `foo?.bar()` and if foo is a valid reference bar() will be executed, if not, nothing will happen.

In addition, Kotlin adds some syntactic sugar to handle the value check. If you want to get the size of a String or -1 if the string is null you could do something like `myString?.length : ? -1` or if you want to do something only if that string exists you can do `myString?.let { print(“Hello $it”) }`.

Using these mechanisms, you will probably say goodbye to the annoying NullPointerException once and for all.

Forget about getters and setters (even IDE generated ones)

Most Java developers have written thousands of “getter” and “setter” methods for their classes. Fortunately, thanks to modern IDEs, you don’t need to type them over and over, however they are there, occupying space in your source file and your brain.

Kotlin replaces them with Data Classes. When you create a data class, Kotlin will auto generate for you a bunch of things. It will create a constructor with your properties and it will generate methods like `isEqual`, `toString` or `hashCode` automatically.

This feature is best explained by seeing an example:

TokBox - Kotlin Example Code 1

The much simpler definition and use of data classes in Kotlin makes development faster by reducing errors and the need to potentially reopen classes to add missing methods, as well as the time it takes other programmers in the team to understand the code. As an example: note that the Java code above is still incomplete!

Kotlin Android Extensions

We have only covered a few key language features here, if you want to check out more strengths of Kotlin, please follow this link to the language website.

In addition to the benefits of the language, there are several further extensions that will make our life easier when working with Kotlin. These are optional, but you are not going to want to live without them once you see them.

Bye bye findViewById and your awful casts

One of the first things I didn’t like when I started android development some years ago was the need to cast every findViewById call:

TextView textView = (TextView)findViewById(R.id.textView);

This is way too much `TextView` for just one line of code! I only want to change the text of my textView, so why do I need to type TextView 4 times, and maybe get it wrong?

Well, Kotlin Android extensions comes to the rescue, you can simply change the text of a textView by doing:

```
import kotlinx.android.synthetic.main_layout.*
textView.text = “”
```

This automatically looks for textView resource id, and converts it to a real TextView instance saving you a lot of boilerplate code. In fact, synthetic properties works converting any component defined in the layout into a variable named as the id. For example, If you have a layout like this:

<RelativeLayout>
    <TextView android:id="@+id/introText"/>
    <RelativeLayout android:id="@+id/inputArea">
        <EditText android:id="@+id/input_room_name"/>
        <Button android:id="@+id/button_join_room"
                ... />
    </RelativeLayout>
    <TextView android:id="@+id/author_label"/>
</RelativeLayout>

You will automatically have variables like introText, inputArea, and button_join_room ready to work with, just by importing this as you usually do with any other Java class.

Using Kotlin Lambdas to Simplify Listeners

Typically, when you need a button to perform some action, you create a instance that implements OnClickListener (which usually will be an anonymous class), declare the method you are overriding, and then write what you want it to actually do. Kotlin as a language provides a simple way to automatically convert a lambda function in the implementation of the method of a interface, if that interface has just one method. In other words, since OnClickListener has just one method, onClick, you can replace all the anonymous class declaration with a lambda expression. Let’s see this much simpler approach in action:

TokBox - Kotlin Example Code 2

Using Kotlin with the OpenTok Android SDK

Kotlin and JavaAs we said at the beginning of this post, Kotlin is fully interoperable with Java, so you can use our OpenTok Android SDK without any problems. We also have a simple multi-party live video app on GitHub which is written entirely in Kotlin. Download this repo to experiment with this code yourself.

In this app, we take advantage of Kotlin synthetic properties to deal with the layout files and to put the subscribers and the publishers views in their place inside the user interface. We also take advantage of data classes to encapsulate the OpenTok session information that usually is flying around the many classes of your app.

We make heavy use of the optional type checking. For example, when we are disconnecting we don’t need to explicitly check that the Publisher or the session is not null. Instead, we just do something simple and clear, like this:

```
mPublisher?.let {
   mSession?.unpublish(it)
   mContainer?.removeView(it.view)
   it.destroy()
}
```

When developing apps using our Android SDK, you will probably also want to take a look at anko. This library, like Kotlin Android Extensions, makes common Android tasks easier. For example, if you want to run some code as a AsyncTask, you can just wrap your code with `doAsync`, if you want to run it on the uiThread you can do the same but wrapping it in a `uiThread` block.

Anko also has other features to work with layouts, logging or sqlite interaction. We make good use of anko in our example app, such as here to start a HTTP request as an async task or here to simplify app logging.

Conclusion – Kotlin and OpenTok

App developers use the OpenTok platform to build sophisticated user experiences that embed live video, audio, screen sharing, annotation and more into all kinds of applications, including social, sports & entertainment, eLearning, telehealth and financial services apps. Building the best and most compelling live experiences takes some work, and any tool that makes this easier, as well as safer and more reliable, is a very “good thing” in our opinion. We recommend taking a serious look at Kotlin for your next Android project with OpenTok.

Although Kotlin was already production ready and is being actively used by many developers worldwide, Google’s decision to convert Kotlin to an official Android language is a big step forward in the adoption of Kotlin inside the Android community. And because Kotlin is JVM based with complete Java integration, you don’t need to go all or nothing with it. If you find this new approach useful, you can start replacing some modules of your app with Kotlin developed ones, and your app will interoperate with the rest of your Java code without any problem. So start using Kotlin today, and please let us know your own OpenTok experiences with Kotlin.

To get started with the OpenTok platform for Live Video, go to our Developer Center for downloads, documentation and sample code: https://tokbox.com/developer.