Android App – Conversion from Java to Kotlin

No Comments

In this article I would like to show in some easy steps the very basics on how to get started with Kotlin for an existing “pure Java” Android project. Depending on the project setup and possible business constraints it might be needed to keep your existing Java source code working for as long as possible, BUT you might want to try out the “new stuff”. I’m referring to the announcement of this years Google I/O conference marking Kotlin as an officially supported programming language for the Android ecosystem.

Let’s get started…

Existing gradle configuration

In an existing Android project there might be a “build.gradle” file in the root directory of the project like this:

// Top-level build file where you can add configuration options common to all sub-projects/modules.
 
buildscript {
 
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
 
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
 
allprojects {
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
}
 
task clean(type: Delete) {
    delete rootProject.buildDir
}

“build.gradle” file in the app module:

apply plugin: 'com.android.application'
 
android {
    compileSdkVersion 25
    buildToolsVersion "26.0.0"
 
    defaultConfig {
        applicationId "de.codecentric.javatokotlin"
        minSdkVersion 19
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
 
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
 
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
 
    implementation 'com.android.support:appcompat-v7:25.4.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    // …
 
    testImplementation 'junit:junit:4.12'
 
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
}

Existing project structure

Existing Android App project structure - Image

Configure Kotlin in project

Android Studio 3.0 provides a tool to configure Kotlin for your project. It is available as a menu entry: Tools > Kotlin > Configure Kotlin in Project.

(Note: If you are using a previous version of Android Studio please install Kotlin plugin first (see Plugin Section under Settings)

Configure Kotlin in Project - Image

After selecting this menu a new overlay appears, where we choose the configurator “Android with Gradle”

Choose configurator - ImageKotlin version - Image

In the next window it is possible to select the Kotlin version to be used. Select “1.1.2-4” as it is the currently supported version by Android Studio 3.0.

After that we can check for changes in our “build.gradle” files:

build.gradle - Image

build.gradle

app/build.gradle - Image

app/build.gradle

The setting of the additional “mavenCentral” repository can be removed as the current project already has JCenter set up in the main build.gradle file for usage in all modules. JCenter should be a superset of the Maven Central repository and is served on Bintray.

Now we should be able to use Kotlin in our project already as it is interoperable and can be called from Java code seamlessly. Just create a simple Kotlin class and try it out for yourselves.

We can even create unit tests using Kotlin and they should work as intended.

With the current project setup it is possible to use Java and Kotlin at the same time side-by-side, but IMHO this setup is not very clean, as it is mixing up both languages in the same directory called „java“.

Language specific directories

Next we want to set up dedicated directories for the Kotlin source code.

In the build.gradle of the app module we need to define additional source sets to let the gradle build script scan these directories as well:

// ...
 
android {
 
    // …
 
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
        test.java.srcDirs += 'src/test/kotlin'
        androidTest.java.srcDirs += 'src/androidTest/kotlin'
    }
}
 
// ...

We need to create the corresponding directories in the file system for sources, unit tests and android instrumentation tests.

Now all existing Kotlin classes and tests can be moved to these newly created directories.

Convert a Java class to Kotlin

The provided Kotlin tools in Android Studio allow to convert existing Java classes to Kotlin as a quick start.

If it is intended to convert the whole Android project to Kotlin, this new project structure helps to keep track on the current conversion state of the app and

  • all classes can be converted,
  • be checked for correctness and
  • be moved to the Kotlin directory

one after the other.

Convert Java class to Kotlin - Image

Resulting project structure

After all the steps from above the project structure should look like this:

Resulting project structure - Image

New Android App Projects

For new projects it is possible to select the option „Include Kotlin support“ directly in the project creation wizard of Android Studio. If it is intended to have language specific directories as mentioned above you can set them up in the same way and follow this guide again.

For further reading, please have a look at the official Android and Kotlin documentations and “Get started with Kotlin” 🙂

https://developer.android.com/kotlin/get-started.html

Lars Schmidt

Lars is member of the codecentric team in Solingen since June 2017. During his career, he has dealt both with the planning and development of middleware systems and their interfaces, as well as with the implementation of mobile applications for end users in the areas of marketing or product development.

Share on FacebookGoogle+Share on LinkedInTweet about this on TwitterShare on RedditDigg thisShare on StumbleUpon

Comment

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