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!
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.
To start, let's create a new Kotlin Multiplatform project using Gradle.
gradle init --type kotlin-multiplatform --dsl kotlin
This will create a new Kotlin Multiplatform project with a default structure.
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.
// src/commonMain/kotlin/com/example/MyKMPProject/CommonFunctions.kt
fun greet(name: String): String {
return "Hello, $name!"
}Now, let's create two target platforms: JVM and JavaScript.
./gradlew kotlin-multiplatform --configure-on-demand jvm
// src/main/kotlin/com/example/MyKMPProject/JvmModuleKt.kt
import com.example.MyKMPProject.CommonFunctions
fun main() {
val name = "World"
println(CommonFunctions.greet(name))
}./gradlew kotlin-multiplatform --configure-on-demand js
// src/main/js/com/example/MyKMPProject/main.js
import { greet } from './commonJs/com-example-MyKMPProject-CommonFunctions.js';
document.getElementById('app').innerHTML = greet('World');<!-- 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>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.
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! 🎉