Working with Kotlin in Android Studio

With the release of M6, we announced support for Android Studio. Let’s take a deeper look at how to get up and running with Android Studio and Kotlin.

Installing the Kotlin Plugin

Much like with IntelliJ IDEA, to install the Kotlin plugin you need to click on Preferences (Settings) and select the Plugins entry. Easiest way is to just start typing plugin as soon as the dialog pops up.

image

Although we can download the plugin and install from disk, the easiest way is to click on the Install JetBrains plugin… and select Kotlin from the list. Right-click and choose Download and Install

image

Follow the instructions to restart the IDE.

Setting up the Project

Android Studio uses Gradle as its build system and part of the effort involved in supporting this environment was adding Gradle support for Kotlin.

Adding Source folder for Kotlin

A typical Android Project has the following layout

image

where the source code for the project is located under the folder main/java. Since we want to use Kotlin (we can mix and match both Java and Kotlin the same project), we need to create a new folder under main, named kotlin. In the Gradle script we’ll later define this folder as a source root.

image

 

Configuring Gradle

We need to set up some dependencies and source folders in the Gradle configuration. Open the build.gradle file and copy the following

Update: Replace “0.6.+” with the version of Kotlin plugin you have installed.

The parts relative to Kotlin are highlighted in bold:

  • Select the Kotlin plugin for Gradle and the version we’re using. The M6 release corresponds to 0.6.69.
  • Apply the kotlin-android plugin
  • Import the Kotlin’s standard library
  • Specifiy where the source code files are located

Specifying the sourceSet will automatically mark the folder we created previously (main/kotlin) as a Source Root in Android Studio.

Once we have the Gradle file updated, we should be able to successfully build Android project written in Kotlin.

Hello World with Kotlin

The easiest way to try out Kotlin with Android is to create a default Android project and convert the code to Kotlin, which the IDE can do for us.

  1. Create a new Android Project (we’ll omit the steps for creating new Android projects).

  2. Add the kotlin folder and update the Gradle file as indicated above.

  3. Select the MainActivity file and from the Code menu select Convert Java File to Kotlin File. We can omit creating a backup.

  4. As soon as we do this, Android Studio automatically detects that this is a Kotlin file and asks us if we want to move it to the kotlin folder. We do so.

Once the project is built we should now be able to run it.

Most likely going to be asked questions

Can I combine Java and Kotlin in the same Android Project?
Absolutely. In fact, check out our GitHub repository for some samples.

Can I use nightly builds of Kotlin?
Yes you can. Just update the Gradle project to point to the snapshots and add the corresponding repository.

Are there any more goodies you forgot to mention?
Now that you ask, we also have some External Annotations for the Android JDK. Android Studio will automatically prompt you to add these to the project.

Although we’ve been using Android Studio in this post, please note that doing Android development with Kotlin is also possible with IntelliJ IDEA and has been available for quite some time. As always, we appreciate any and all feedback.

This entry was posted in Tools and tagged , . Bookmark the permalink.

18 Responses to Working with Kotlin in Android Studio

  1. What is the overhead? Compile Time, APK size, with or without proguard.

    Note that with Scala the cumbersome part is not the language itself but scala-library.jar. Which is why I ask for proguard.

    • Hadi Hariri says:

      We’ve not run specific tests yet for Android, but, unlike Scala, our runtime is small and the code performs as fast as Java on most benchmarks.

    • fanchao says:

      I had an investigation on the potential performance impacts on Android today. What I did is decompiling the .class file generated by Kotlin and some interesting facts I concerned most compared to other framework/language:

      Inline functions (lambda expressions) are inlining wherever possible.
      For example, no penalty for using forEach expression, it’s just like hand writing a Java loop, no extra inner classes, no extra object allocated. But what I know for Java 8 or similar things that support streaming API will create an anonymous inner class instance and invoke the method each time for a value, which seems to be a unnecessary performance hole on Android.
      Of course, if you assign a lambda as Java interface, a new inner class will be generated, it’s not winning over Java but at least it’s not losing (Java will generate one, too).

      Auto boxing/unboxing taken care of.
      Primitive types will be used wherever possible. Arrays and it’s family seem to be generic (which produces boxing/unboxing) but you always have the choice to use IntArray or sort of things, where it will try to use primitive arrays and values directly.

      Optional getter/setters.
      Unlike some other JVM languages that generate getter/setter for property, Kotlin can make use of field access if a backing field is declared by ‘private’, no getter/setters will be generated. Android performance guide outlines getter/setters issues, basically the idea is redundant methods or calls should be avoided.

      Code generation for extension is clean and direct
      For extensions, just an extra static method that takes the injected class’ instance as the first argument will be generated for you, it’s like just writing a Utility method.

      As a neat freak of generated codes, anything that is more than plain Java looks scare to me. A good compiler should not compromise performance and expressiveness . I think from what I observed, one can expect a same performance level with Java, even you use the Kotlin specified idioms (lambda, , not a Kotlin version of Java code.

  2. evilbloodydemon says:

    Why app and kotlin library sources is placed to resulting .apk?

  3. Stuart Rackham says:

    I also had to set the kotlin folder as belonging to project sources otherwise you’ll get a “default activity not found” error message (I’m using Studio 0.2.8 with Kotlin plugin 0.6.350 on Linux), the plugin did not do this automatically as the article suggests. Right-click on the kotlin directory (in the Project Tool window) and select the ‘Mark Directory As->Sources Root’ menu command (you can also manage this from the ‘Project Structure’ dialog.

  4. Stuart Rackham says:

    Mark the kotlin folder as a source root at step 2 (in ‘Hello World with Kotlin’ above) to ensure you get automatically prompted to move the converted Kotlin file to the kotlin folder.

  5. Pingback: Piotr Wittchen » Hello Kotlin!

  6. Marcin Koziński says:

    Wouldn’t it be possible for kotlin-android plugin to add src/main/kotlin to sourceSets?

    I was thinking of writing a gradle code snippet to add kotlin source set for each java source set. It seems to be possible. And the best place for such code would inside the first party plugin :)

    • Natalia Ukhorskaya says:

      kotlin-android plugin already add src/main/kotlin to sourceSets. The only reason why you need to do this is to make IDE know that src/main/kotlin is a source directory. And we are going to fix it.

  7. Lemuel Adane says:

    I just update my Android Studio, and for the first time install the latest Kotlin plugin, and followed what the article said on my Mac. After several wasted hours of figuring out, I still had 3 errors, Its saying that ‘it was compiled with incompatible version of Koltlin.’ and ABI was this version but expected was this version. Wow! I don’t even have an older version of Kotlin. And what’s ABI? Are they talking to themselves? Im sorry but I got disapointed.

  8. Igor says:

    I’v hat this error when syncing hradle project:

    What it is and what I need to do?

    • Natalia Ukhorskaya says:

      You are using SNAPSHOT version of kotlin. Have you added http://oss.sonatype.org/content/repositories/snapshots url to your repositories list? If yes, could you report us an issue with your build.gradle file attached? Thanks!

      • Igor says:

        Thank you so much, It works but I’v take new error:

        • Natalia Ukhorskaya says:

          Could you provide you build.gradle file please?

          • Igor says:

            buildscript {
            ext.kotlin_version = ’0.11.91′
            repositories {
            mavenCentral()
            maven {
            url ‘http://oss.sonatype.org/content/repositories/snapshots’
            }
            }
            dependencies {
            classpath ‘org.jetbrains.kotlin:kotlin-gradle-plugin:0.6.+’
            classpath ‘com.android.tools.build:gradle:1.0.+’
            classpath “org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version”
            }
            }
            apply plugin: ‘kotlin-android’
            dependencies {
            compile ‘org.jetbrains.kotlin:kotlin-stdlib:0.6.+’
            compile “org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version”
            }

            android {
            compileSdkVersion 17
            buildToolsVersion “17.0.0″

            }

      • Igor says:

        Thank you, It worked but now I’v take new error:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">