[Part 2] Seamlessly Integrate Kotlin Multiplatform(KMP) into Your Android Project

Jyoti Sheoran
3 min readMay 19, 2024

--

Kotlin Multiplatform(KMP) allows you to share code between Android and iOS applications, making development faster and more efficient.

This guide will walk you through the steps to integrate KMP into an existing Android project, ensuring that you can leverage shared code without compromising the unique features of your Android app.

This is Part 2 of the KMP series: How to Integrate Kotlin Multiplatform (KMP) into Your Native Apps. If you haven’t already, you can check out Part 1: All about Kotlin Multiplatform for an introduction and overview of KMP.

Prerequisites:

  • An existing Android App.

Step 1: Create a KMP Module

  • In Android Studio, go to File -> New -> New Module.
  • Select KMP Shared Module.

In new android studio, if you are not able to find KMP Shared Module, don’t worry its hidden in settings.

Go to settings -> search kmm -> enable experimental kmm shared module.

Step2: Update Build Scripts for Kotlin DSL (if necessary)

If the Android project fails to build, it is likely that the KMP module uses Kotlin DSL. Replace the dependency configuration in shared/build.gradle.kts with:

plugins {
id("com.android.library")
id("org.jetbrains.kotlin.multiplatform")
}

kotlin {
android()
sourceSets {
val androidMain by getting {
dependencies {
implementation("org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version")
}
}
}
}

For testing dependencies, add:

dependencies {
implementation("org.jetbrains.kotlin:kotlin-test:$kotlin_version")
}

Step3: Build and Verify

  • Sync your project with Gradle files and ensure that the build completes successfully.
  • Address any issues that arise during the build process.
  • Now your app’s project structure looks like this, it will have app and shared module.

Step 4: Include shared in app module

  • Open settings.gradle and ensure the KMP module dependency is added (this would be done automatically).
  • In your app/build.gradle file, add the following dependencies:
implementation project(":shared")

Step5: Use Shared Code in app

  • You can now use the shared code from the KMP module in your Android project. For example, import shared classes and functions as needed in your Android activities or fragments.

Step6: Build and Verify

  • Run your Android project to verify that everything is integrated correctly and that the shared code functions as expected.

By following these steps, you can successfully integrate KMP into your existing Android project, allowing you to share code seamlessly between Android and other platforms, enhancing your development process and reducing duplication of effort.

Stay tuned for the next part of this series, where we will explore integrating KMP into an existing iOS project.

--

--

Jyoti Sheoran
Jyoti Sheoran

Responses (3)