Kotlin Multiplatform Gradle Tutorial 🎯

beginner
7 min

Kotlin Multiplatform Gradle Tutorial 🎯

Welcome to our comprehensive guide on Kotlin Multiplatform Gradle! In this lesson, we'll explore how to leverage Kotlin's multiplatform capabilities with Gradle to write shared code across multiple platforms. Let's dive in!

What is Kotlin Multiplatform? 📝

Kotlin Multiplatform (KMP) is a technology that allows you to write shared code in Kotlin that can be compiled to multiple platforms, such as JVM, JavaScript, iOS, and more. This enables you to reuse your codebase across different projects, reducing duplication and increasing productivity.

Setting Up the Project 💡

To start, let's create a new Kotlin Multiplatform project using Gradle.

  1. Open your terminal or command prompt and navigate to your desired project directory.
  2. Run the following command:
gradle init --type kotlin-multiplatform --dsl kotlin

This will create a new Kotlin Multiplatform project with a default structure.

Common Module ✅

The Common Module contains shared logic that can be used across all target platforms. Let's create a simple function in the commonMain source set.

kotlin
// src/commonMain/kotlin/com/example/MyKMPProject/CommonFunctions.kt fun greet(name: String): String { return "Hello, $name!" }

Targeting Platforms 💡

Now, let's create two target platforms: JVM and JavaScript.

JVM Module

  1. Run the following command to create a new JVM module:
./gradlew kotlin-multiplatform --configure-on-demand jvm
  1. In the newly created JVM module, import the shared function from the Common Module:
kotlin
// src/main/kotlin/com/example/MyKMPProject/JvmModuleKt.kt import com.example.MyKMPProject.CommonFunctions fun main() { val name = "World" println(CommonFunctions.greet(name)) }

JavaScript Module

  1. Run the following command to create a new JavaScript module:
./gradlew kotlin-multiplatform --configure-on-demand js
  1. In the newly created JavaScript module, import the shared function from the Common Module and use it in a simple HTML file:
javascript
// src/main/js/com/example/MyKMPProject/main.js import { greet } from './commonJs/com-example-MyKMPProject-CommonFunctions.js'; document.getElementById('app').innerHTML = greet('World');
html
<!-- src/main/resources/main/index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My KMP Project</title> </head> <body> <div id="app"></div> <script src="main.js"></script> </body> </html>

Building and Running ✅

To build and run the project, use the following command:

./gradlew build

This will compile the shared code and generate the artifacts for each platform. You can then run the JVM module with:

./gradlew jvmMain

And open the JavaScript module in a web browser.

Quiz 💡

That's it for this lesson! In the next tutorial, we'll delve deeper into Kotlin Multiplatform, exploring more advanced features and best practices. Happy coding! 🎉