Kotlin For Android: An Introduction

See how Kotlin For Android makes developing Android apps far more enjoyable. Learn how simple it is by creating your very own book searching app. By Matei Suica.

Leave a rating/review
Download materials
Save for later
Share

Update Note: Matei Suica updated to this tutorial to Android Studio 3.3. Joe Howard made the previous update, and Eunice Obugyei wrote the original tutorial.

Before 2017, Android app developers almost exclusively used the Java 6 programming language, with support following for later additions. Java 6 was introduced in 2006, two years before the release of Android devices.

JetBrains developed IntelliJ IDEA, which is the basis for Android Studio. In 2011, the company introduced the Kotlin language, but few Android developers started using it. Though Kotlin was production ready, the language wasn’t stable. When important changes in the language happened, developers had to change their codebase. Five years later, Kotlin released 1.0. Thanks to all the early adopters for this great moment!

At Google I/O 2017, Google announced that Android will support Kotlin as a first-class programming language from now on. For this to happen, the 3.0 release of Android Studio (AS) integrated Kotlin support out of the box! The following three minor releases of AS continued to improve the Kotlin support and the tools available.

Kotlin is a statically-typed, modern programming language that runs on a Java Virtual Machine (JVM) by compiling Kotlin code into Java byte-code. It can also be compiled to JavaScript source code and to native executables. Kotlin is flexible and has some cool features!

In this Kotlin for Android tutorial, you’ll learn:

  • How to set up your Kotlin environment.
  • How to work with Java and Kotlin in the same project.
  • What makes Kotlin so exciting as a new language.
Note: This tutorial assumes you’re experienced in Android development with Java. If you’re new to the Android world or have big questions about the starter project, please review other Android tutorials. For this tutorial, you need Android Studio 3.3 or later.

Why Kotlin For Android?

Since Android took the world by storm, developers have had few alternatives to Java for app development. Java was the programming language that the most advanced phones were using to run their native apps on their proprietary operating systems. For example, Nokia’s Symbian had Java ME apps. Although its usage is widespread, Java comes with a lot of historical baggage.

Java 8 solved some language issues and even more were corrected with Java 9 and 10. Unfortunately, you have to set the minimum SDK to Android 24 to use all of Java 8’s features, which isn’t an option for many developers. The fragmentation of the Android ecosystem makes it impossible to leave out users with older devices. For most developers, Java 9 and 10 aren’t even on the radar.

Kotlin is the modern programming language solution for Android. There are a few things that make Kotlin a great fit for Android:

  1. Compatibility: It’s compatible with JDK 6, so older devices aren’t left behind.
  2. Performance: It’s on par with Java.
  3. Interoperability: It’s 100% interoperable with Java including annotations.
  4. Footprint: The runtime library for Kotlin is tiny.
  5. Compilation Time: There’s a little overhead on clean builds but it’s way faster with incremental builds.
  6. Learning Curve: It’s easy to learn, especially for people used to modern languages. The Java to Kotlin converter in IntelliJ and Android Studio makes it even easier. You can also use a mix of Kotlin and Java in a project, so take your time learning Kotlin and add it in when you feel comfortable.

While Java 8 is now supported on recent Android releases, recent developer surveys say that Kotlin is gaining ground. The Realm team notes that ”Kotlin is about to change the whole Android ecosystem.” Kotlin is now one of the most loved programming languages out there. It’s poised to dominate Android app development. Above all, it’s a new language! What could be more exciting? iOS developers had their fun in 2014 with Swift. Now, it’s your turn. :]

Getting Started

For this tutorial, you’ll explore Kotlin by working with an app that allows users to search for books, see book covers and share books with friends.

Download the materials using the Download Materials button at the top or at the bottom of this page. Extract and open the starter project in Android Studio 3.3 or later.

It contains three source code files written in Java:

  • MainActivity.java: An Activity that displays the screen for searching and displaying a list of books.
  • DetailActivity.java: An Activity that displays the book cover for the ID passed to it.
  • JSONAdapter.java: A custom BaseAdapter that transforms a JSON object into a list view item.

Build and run the project to see what you’re working with.

First things first: Enter your name so that the app can greet you! :]

After that, start searching for the books you’re interested in. Type a book or author name in the field and click on Search to get a list of books.

Clicking on a row takes you to the second screen where you’ll have the full cover to admire. Isn’t it cool?

Setting up Your Environment

Android Studio 3.3 and later support Kotlin right out of the box. Any new projects you create will use Kotlin. Set the language to Kotlin when you create a new activity. You won’t need to create a project for this tutorial since it’s provided as a starter project above:

A popup will encourage you to update your Kotlin plugin in Android Studio 3.3 whenever a new version is available. You can always check your Kotlin plugin version on the Plugins screen by clicking command+shift+a and typing Plugins. Type Kotlin into the search box and check the version on the right:

Working With Java and Kotlin Together

One of the most amazing qualities of Kotlin is that it can coexist with Java. Java code can call Kotlin code and vice versa. You might not even notice that you’re calling code in another language!

From this point forward, you’ll be translating the DetailActivity class into Kotlin.

Single click com.raywenderlich.android.omgandroid in the Project panel on the left-hand side. With the package selected, go to File ▸ New ▸ Kotlin File/Class to create a new Kotlin class. Without the package selected, you won’t see the Kotlin file option.

On the New Kotlin File/Class popup, select Class in the Kind field and enter DetailActivityKotlin as the class name. Click OK.

intro_to_kotlin_17

Your new class should look like this:

    
package com.raywenderlich.android.omgandroid

class DetailActivityKotlin {
}

A few things to note:

  1. Declare Kotlin classes using the keyword class — just like in Java.
  2. By default, if no visibility modifier is present in Kotlin, the item is public.
  3. Classes and methods are final by default. Declare them open if you want to inherit classes and override methods.

Since Kotlin and Java are interoperable, you can use existing Java frameworks and libraries in your Kotlin code files.

Make the class a subclass of AppCompatActivity:

  
class DetailActivityKotlin : AppCompatActivity() {

}

If needed, click Option + Return to import classes such as AppCompatActivity. Android Studio will usually add the import statements for you if there are no conflicts.

Distinctly from Java, in Kotlin, you append :NameOfParentClass() to the subclass declaration. The trailing parentheses are for the constructor on the parent class.

Now override Activity‘s onCreate() method. It will look something like this:

  
import android.app.Activity
import android.os.Bundle

class DetailActivityKotlin: Activity() {

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

intro_to_kotlin_18

Note: You can use Android Studio’s code generation functionality to generate the onCreate method. Press Control + O to see a popup with all overridable methods for the class you’re in and choose onCreate.

Open MainActivity.java and replace the DetailActivity reference in onItemClick() with DetailActivityKotlin.

Your intent creation line should change from:

  
Intent detailIntent = new Intent(this, DetailActivity.class);

To this:

  
Intent detailIntent = new Intent(this, DetailActivityKotlin.class);
Matei Suica

Contributors

Matei Suica

Author and Author

Nicole Hardina

Editor

Over 300 content creators. Join our team.