NOTE: These instructions for upgrading an existing project with Kotlin support is for codebases that are using Gradle 4 (Gradle Plugin version 3.x.x)

To provide support for Kotlin in a project that only has Java support, try the following:

  • add the latest Kotlin version number as a static variable in the buildscript section
  • add the Kotlin class path to dependencies

Updates to Project gradle file:

buildscript {
    ext.kotlin_version = "1.2.61"
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.4'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

Updates to Module: app gradle file:

  • add two plugins to the top of the file: kotlin-android and kotlin-android-extensions
  • add org.jetbrains.kotlin:kotlin-stdlib-jdk7 to the dependencies.
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    // Kotlin support
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

Once these updates are made in Android Studio, try building/running the code and make sure everything looks ok.

From here take a look at the shortcuts below to convert existing Java files to Kotlin code.

How to convert your Java file to Kotlin:

use Shift-Alt-Cmd-K or Shift-Shift + search Convert Java File to Kotlin File.

Leave a Reply