1. Code
  2. Coding Fundamentals
  3. Tools

How to Use Kotlin in Your Android Projects

Scroll to top

Introduction

Kotlin, the open source programming language designed by JetBrains, is becoming increasingly popular among Java developers. It is often touted as Java's successor. Compared to Java, it offers a richer development experience, because it is more modern, expressive, and concise.

If you are looking for an alternative programming language for Android development, you should give Kotlin a try. It can easily be used instead of or alongside Java in your Android projects.

In this tutorial, I will show you how to use Kotlin and Kotlin plugins in your Android Studio projects.

Prerequisites

To follow along with me, you need to have:

  • the latest version of Android Studio
  • a basic understanding of Kotlin syntax

If you're unfamiliar with the Kotlin programming language, then I recommend reading the Getting Started section of the Kotlin reference to get up to speed with the language.

1. Installing Kotlin Plugins

In Android Studio's quick start menu, select Configure > Plugins.

Configure PluginsConfigure PluginsConfigure Plugins

In the next screen, click Install JetBrains plugin... at the bottom.

Install JetBrains pluginInstall JetBrains pluginInstall JetBrains plugin

Select Kotlin Extensions For Android from the list and click Install Plugin on the right.

Install Kotlin Extensions For AndroidInstall Kotlin Extensions For AndroidInstall Kotlin Extensions For Android

Because the plugin depends on the Kotlin plugin, you will be asked to install both. Click Yes to begin the installation.

Plugin Dependencies DetectedPlugin Dependencies DetectedPlugin Dependencies Detected

When the installation completes, restart Android Studio to activate the plugins.

2. Creating a Kotlin Activity

In Android Studio, right-click the name of your package and select New > Kotlin File.

New  Kotlin FileNew  Kotlin FileNew  Kotlin File

In the dialog that pops up, enter the name of the new Activity and select Class from the drop-down list. I've named my class MainActivity.

New Kotlin file dialogNew Kotlin file dialogNew Kotlin file dialog

Once the class has been created, you will see an alert asking you to configure your app module to support Kotlin.

Configure Kotlin alertConfigure Kotlin alertConfigure Kotlin alert

Click the link in the alert and, in the dialog that pops up, click OK to choose the default values.

Configure Kotlin dialogConfigure Kotlin dialogConfigure Kotlin dialog

To configure your project to support Kotlin, the Kotlin plugin makes several changes in the build.gradle file. Apply these changes by clicking the Sync Now button as shown below.

Sync Now pop upSync Now pop upSync Now pop up

At this point, your project's configuration is complete. Go back to the Kotlin class you created a moment ago to start coding in Kotlin.

3. Using Kotlin

To keep the example simple, I will be showing you how to create an Activity with a single TextView that displays a String.

Make sure your class is a subclass of Activity and override its onCreate method. Of course, you have to do that in Kotlin. If you are new to Kotlin, I suggest you use Android Studio's code generation functionality by pressing Control+O to get the method signatures right.

Override Members dialogOverride Members dialogOverride Members dialog

Your class should now look like this:

1
package com.hathy.kotlinsample
2
3
import android.app.Activity
4
import android.os.Bundle
5
6
public class MainActivity: Activity() {
7
    override fun onCreate(savedInstanceState: Bundle?) {
8
        super.onCreate(savedInstanceState)
9
    }
10
}

Create an instance of TextView as an assign-once local variable by using the val keyword.

1
val myMessage = TextView(this)

Call its setText method to set the String you want to display and then call setContentView to display the text view.

1
myMessage.setText("Hello")
2
setContentView(myMessage)

Like you would for a Java Activity, you need to declare your Kotlin Activity in your app's AndroidManifest.xml for it to be recognized by the Android system. If this is the only Activity in your project, your manifest file should look like this:

1
<activity android:name=".MainActivity">
2
    <intent-filter>
3
        <action android:name="android.intent.action.MAIN"/>
4
        <category android:name="android.intent.category.LAUNCHER"/>
5
    </intent-filter>
6
</activity>

You can now compile and run your app on your Android device or emulator. While the Kotlin compiler is slightly slower than that of Java, you are unlikely to see any significant change in your project's build time.

4. Using Kotlin Android Extensions

The Kotlin Android Extensions plugin lets you treat the widgets you define in the layout XML of an Activity as if they were properties of that Activity. In other words, if you use this plugin, you will never have to call findViewById. These properties are aptly called synthetic properties.

To use this feature in your app, you need to add org.jetbrains.kotlin:kotlin-android-extensions as a build script dependency in your app module's build.gradle as shown below. Don't forget to click the Sync Now button to sync your project.

1
buildscript {
2
    dependencies {
3
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
4
    }
5
}

Let's now create an Activity similar to the one we created in the previous step, but use a layout XML to define the TextView. Create a new layout XML file named another_activity.xml. In the layout XML file, define a TextView with an id of myMessage.

1
<?xml version="1.0" encoding="utf-8"?>
2
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3
    android:orientation="vertical" android:layout_width="match_parent"
4
    android:layout_height="match_parent">
5
6
    <TextView
7
        android:layout_width="wrap_content"
8
        android:layout_height="wrap_content"
9
        android:textAppearance="?android:attr/textAppearanceLarge"
10
        android:text="Large Text"
11
        android:id="@+id/myMessage" />
12
</LinearLayout>

Create another Kotlin class, AnotherActivity, that extends Activity and override its onCreate method. This is what the implementation should look like:

1
package com.hathy.kotlinsample
2
3
import android.app.Activity
4
import android.os.Bundle
5
6
public class AnotherActivity: Activity() {
7
8
    override fun onCreate(savedInstanceState: Bundle?) {
9
        super.onCreate(savedInstanceState)
10
    }
11
}

Call setContentView in the onCreate method to use the layout XML you just created as the layout of this Activity.

1
setContentView(R.layout.another_activity)

Now, instead of calling findViewById to get a reference to the TextView, you can import it using the following code snippet:

1
import kotlinx.android.synthetic.another_activity.myMessage

If you had more widgets in your layout, you can import all of them using the following code snippet:

1
import kotlinx.android.synthetic.another_activity.*

You can now access your TextView using its id as if it were a property of the Activity class. For example, to change the text of the TextView, you can write:

1
myMessage.setText("Hello")

5. Converting Java Classes to Kotlin

You can use the Kotlin plugin to convert existing Java classes to Kotlin classes. To try this feature, create a new Java class with the following implementation. It's a simple Activity that logs the sum of two integers.

1
public class YetAnotherActivity extends Activity {
2
3
    private int a,b;
4
5
    @Override
6
    protected void onCreate(Bundle savedInstanceState) {
7
        super.onCreate(savedInstanceState);
8
        a=10;
9
        b=20;
10
        Log.d("MESSAGE", "The sum is "+(a+b));
11
    }
12
}

Convert the Java class to a Kotlin class by pressing Control+Alt+Shift+J, or, from the menu, selecting Code > Convert Java File to Kotlin File.

Convert Java file to Kotlin fileConvert Java file to Kotlin fileConvert Java file to Kotlin file

After the conversion, your class will look like this:

1
public class YetAnotherActivity : Activity() {
2
3
    private var a: Int = 0
4
    private var b: Int = 0
5
6
    override fun onCreate(savedInstanceState: Bundle?) {
7
        super.onCreate(savedInstanceState)
8
        a = 10
9
        b = 20
10
        Log.d("MESSAGE", "The sum is " + (a + b))
11
    }
12
}

You will also notice that the file's extension has changed from .java to .kt.

Conclusion

In this tutorial, you have learned how to use Kotlin in your Android projects after installing the Kotlin plugin and the Kotlin Android Extensions plugin for Android Studio. As Kotlin and Java classes are largely interoperable, if you are still learning Kotlin, it is best to introduce it in your Android projects gradually.

To learn more about Kotlin, I recommend browsing the Kotlin reference. The Getting Started section will help you get up to speed with this new language.


Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.