Beliebte Suchanfragen

Cloud Native

DevOps

IT-Security

Agile Methoden

Java

//

Android App – Conversion from Java to Kotlin

12.7.2017 | 4 minutes of reading time

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:

1// Top-level build file where you can add configuration options common to all sub-projects/modules.
2 
3buildscript {
4 
5    repositories {
6        maven { url 'https://maven.google.com' }
7        jcenter()
8    }
9    dependencies {
10        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
11 
12        // NOTE: Do not place your application dependencies here; they belong
13        // in the individual module build.gradle files
14    }
15}
16 
17allprojects {
18    repositories {
19        maven { url 'https://maven.google.com' }
20        jcenter()
21    }
22}
23 
24task clean(type: Delete) {
25    delete rootProject.buildDir
26}

“build.gradle” file in the app module:

1apply plugin: 'com.android.application'
2 
3android {
4    compileSdkVersion 25
5    buildToolsVersion "26.0.0"
6 
7    defaultConfig {
8        applicationId "de.codecentric.javatokotlin"
9        minSdkVersion 19
10        targetSdkVersion 25
11        versionCode 1
12        versionName "1.0"
13        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
14    }
15 
16    buildTypes {
17        release {
18            minifyEnabled false
19            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
20        }
21    }
22}
23 
24dependencies {
25    implementation fileTree(dir: 'libs', include: ['*.jar'])
26 
27    implementation 'com.android.support:appcompat-v7:25.4.0'
28    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
29    // …
30 
31    testImplementation 'junit:junit:4.12'
32 
33    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
34        exclude group: 'com.android.support', module: 'support-annotations'
35    })
36}

Existing project structure

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)

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

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

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:

1// ...
2 
3android {
4 
5    // …
6 
7    sourceSets {
8        main.java.srcDirs += 'src/main/kotlin'
9        test.java.srcDirs += 'src/test/kotlin'
10        androidTest.java.srcDirs += 'src/androidTest/kotlin'
11    }
12}
13 
14// ...

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.

Resulting project structure

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

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

share post

Likes

0

//

More articles in this subject area

Discover exciting further topics and let the codecentric world inspire you.

//

Gemeinsam bessere Projekte umsetzen.

Wir helfen deinem Unternehmen.

Du stehst vor einer großen IT-Herausforderung? Wir sorgen für eine maßgeschneiderte Unterstützung. Informiere dich jetzt.

Hilf uns, noch besser zu werden.

Wir sind immer auf der Suche nach neuen Talenten. Auch für dich ist die passende Stelle dabei.