Hello World written in Kotlin using Android Studio

Sat Mar 15, 2014

Kotlin is Jetbrains successor to Java, it’s evolving rapidly and what documentation there is for writing Android apps is pretty soon out of date to the point where even getting the canonical Hello World up and running can be a frustrating experience.

Here’s how to get a Kotlin version Hello World running on Android using Android Studio 0.5.1.

IMPORTANT: This is based on Android Studio 0.5.1 and Kotlin 0.7.115 (the latest versions when I wrote this post) – it will probably be broken on other versions Studio/Kotlin.

Assuming you have already installed Android Studio, Follow these instructions:

  1. Install the nightly build of the Kotlin plugin in Android Studio (I had to add the Kotlin plugin repository manually because it was not in the list of JetBrains plugins, though it will probably reappear once Android Studio and Kotlin begin to stabilize):
    1. Open the Settings dialog and go to the Plugins section.
    2. Click Browse Repositories…
    3. Click Manage Repositories…
    4. Add the following IDEA 13 EAP repository URL http://teamcity.jetbrains.com/guestAuth/repository/download/bt345/.lastSuccessful/updatePlugins.xml
    5. Search for the kotlin-plugin in the Browse Repositories dialog; right-click on it and select Download and install.
  2. Create a Java version of Hello World: From the Android Studio File menu select New Project… and set the Application name to HelloKotlin (or whatever takes you fancy) and accept all the remaining New Project Wizard settings.
  3. Rename the app/src/main/java directory to app/src/main/kotlin (right-click on the app/src/main/kotlin directory in the Project Tool window and select the Refactor->Rename… menu command).
  4. Open the app/src/main/kotlin/MainActivity.java file in the editor and run the Code->Kotlin->Convert Java File to Kotlin File menu command (no need to save a backup).
  5. Run the Tools->Kotlin->Configure Kotlin in Project menu command – this will update the project’s build.gradle file with Kotlin libraries, plugins and other Kotlin specific configuration requirements.
  6. Now compile and build the project using the Build->Make Project menu command.

Because the Java to Kotlin converter does not differentiate between nullable and non-nulable Java method arguments you will get compilation errors and you need to manually modify the converted Kotlin source code. The error messages are not always self explanatory e.g. this error 'onCreate' overrides nothing in this line:

override fun onCreate(savedInstanceState: Bundle) {

Is resolved by making the savedInstanceState argument nullable:

override fun onCreate(savedInstanceState: Bundle?) {

This error Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver in this line:

val id = item.getItemId()

Is because the item method argument has been made nullable, it can be resolved using the safe call operator:

val id = item?.getItemId()

Here’s the resulting app/src/main/kotlin/MainActivity.kt file:

package com.example.hellokotlin.app

import android.support.v7.app.ActionBarActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem


public class MainActivity() : ActionBarActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }


    override fun onCreateOptionsMenu(menu: Menu?): Boolean {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        val id = item!!.getItemId()
        if (id == R.id.action_settings) {
            return true
        }
        return super.onOptionsItemSelected(item)
    }

}

Here’s the Gradle build file (app/build.gradle) which required no manual editing – it was created by the New Project wizard and updated by the Kotlin plugin Tools->Kotlin->Configure Kotlin in Project menu command:

apply plugin: 'android'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.1"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:+'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile "org.jetbrains.kotlin:kotlin-stdlib:$ext.kotlin_version"
}
buildscript {
    ext.kotlin_version = '0.7.115'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$ext.kotlin_version"
    }
}
repositories {
    mavenCentral()
}


  « Previous: Next: »