Kotlin MPP Setup
Introduction
Kotlin Multiplatform Project (MPP) is a powerful framework that allows developers to share code between different platforms such as Android, iOS, web, and desktop applications. By writing the business logic once and sharing it across platforms, you can significantly reduce development time and ensure consistency across your applications.
In this guide, we'll walk through the process of setting up a Kotlin Multiplatform project from scratch. We'll cover everything from installing the necessary tools to creating a basic project structure that you can use as a foundation for your multiplatform applications.
Prerequisites
Before we dive into setting up a Kotlin MPP project, make sure you have the following tools installed:
- JDK (Java Development Kit) 11 or later
- Android Studio (latest version recommended)
- Xcode (if targeting iOS, latest version recommended)
- Git (for version control)
Step 1: Installing Kotlin
While Android Studio comes with Kotlin support out of the box, make sure you have the latest version installed. You can check your Kotlin version by running:
kotlin -version
If you need to install or update Kotlin, you can do so through SDKMAN:
# Install SDKMAN
curl -s "https://get.sdkman.io" | bash
# Install Kotlin
sdk install kotlin
Step 2: Creating a New Kotlin Multiplatform Project
Using Android Studio
- Open Android Studio
- Click on "New Project"
- Select "Kotlin Multiplatform App" from the project templates
- Configure your project with appropriate names and package
Using the Command Line
If you prefer using the command line, you can create a new Kotlin Multiplatform project using the following commands:
# Create a new directory for your project
mkdir MyKMPProject
cd MyKMPProject
# Initialize with Gradle wrapper
gradle wrapper --gradle-version 7.4.2
# Create basic project structure
mkdir -p src/commonMain/kotlin
mkdir -p src/androidMain/kotlin
mkdir -p src/iosMain/kotlin
Step 3: Setting Up the Gradle Files
Kotlin Multiplatform projects rely heavily on Gradle for build configuration. Let's set up the necessary Gradle files:
Root build.gradle.kts
buildscript {
repositories {
gradlePluginPortal()
google()
mavenCentral()
}
dependencies {
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.0")
classpath("com.android.tools.build:gradle:7.4.0")
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
Module build.gradle.kts
plugins {
kotlin("multiplatform")
id("com.android.library")
}
kotlin {
android()
listOf(
iosX64(),
iosArm64(),
iosSimulatorArm64()
).forEach {
it.binaries.framework {
baseName = "shared"
}
}
sourceSets {
val commonMain by getting {
dependencies {
// Common dependencies
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
}
}
val commonTest by getting {
dependencies {
implementation(kotlin("test"))
}
}
val androidMain by getting {
dependencies {
// Android-specific dependencies
implementation("androidx.core:core-ktx:1.9.0")
}
}
val androidTest by getting {
dependencies {
implementation("junit:junit:4.13.2")
}
}
val iosX64Main by getting
val iosArm64Main by getting
val iosSimulatorArm64Main by getting
val iosMain by creating {
dependsOn(commonMain)
iosX64Main.dependsOn(this)
iosArm64Main.dependsOn(this)
iosSimulatorArm64Main.dependsOn(this)
dependencies {
// iOS-specific dependencies
}
}
}
}
android {
compileSdk = 33
sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
defaultConfig {
minSdk = 24
targetSdk = 33
}
}
settings.gradle.kts
pluginManagement {
repositories {
google()
gradlePluginPortal()
mavenCentral()
}
}
rootProject.name = "MyKMPProject"
include(":shared")
Step 4: Creating a Sample Shared Module
Let's create a simple "Hello World" implementation that can be shared across platforms:
src/commonMain/kotlin/com/example/Greeting.kt
package com.example
class Greeting {
fun greet(): String {
return "Hello, Kotlin Multiplatform!"
}
}
src/androidMain/kotlin/com/example/Platform.kt
package com.example
actual class Platform actual constructor() {
actual val platform: String = "Android ${android.os.Build.VERSION.SDK_INT}"
}
src/iosMain/kotlin/com/example/Platform.kt
package com.example
import platform.UIKit.UIDevice
actual class Platform actual constructor() {
actual val platform: String = UIDevice.currentDevice.systemName() + " " + UIDevice.currentDevice.systemVersion
}
src/commonMain/kotlin/com/example/Platform.kt
package com.example
expect class Platform() {
val platform: String
}
fun getPlatformGreeting(): String {
return "Hello from ${Platform().platform}!"
}
Step 5: Building and Running Your Project
After setting up your project, you can build it using the following Gradle command:
./gradlew build
To run tests across all platforms:
./gradlew allTests
Real-World Application: Building a Cross-Platform Calculator
Let's create a simple calculator logic that can be shared across platforms:
src/commonMain/kotlin/com/example/Calculator.kt
package com.example
class Calculator {
fun add(a: Double, b: Double): Double = a + b
fun subtract(a: Double, b: Double): Double = a - b
fun multiply(a: Double, b: Double): Double = a * b
fun divide(a: Double, b: Double): Double {
if (b == 0.0) throw IllegalArgumentException("Cannot divide by zero")
return a / b
}
}
This calculator class can now be used in both Android and iOS applications:
Android Usage:
// In your Android activity or fragment
val calculator = Calculator()
val result = calculator.add(5.0, 3.0)
println("5 + 3 = $result")
// Output: 5 + 3 = 8.0
iOS Usage (Swift):
// In your iOS view controller
let calculator = Calculator()
let result = calculator.add(5.0, 3.0)
print("5 + 3 = \(result)")
// Output: 5 + 3 = 8.0
Common Issues and Solutions
Problem: Gradle Sync Fails
Solution: Make sure you're using compatible versions of Kotlin, Gradle, and the Android Gradle Plugin. Check for any error messages in the Gradle console and update dependencies accordingly.
Problem: iOS Framework Not Found
Solution: Make sure you've properly set up the iOS framework export in your Kotlin module:
kotlin {
ios() {
binaries {
framework {
baseName = "shared"
}
}
}
}
Problem: Expected/Actual Class Mismatch
Solution: Ensure that your expect
and actual
declarations match exactly, including property names and function signatures.
Summary
In this guide, we've covered the essential steps to set up a Kotlin Multiplatform Project:
- Installing the necessary tools and prerequisites
- Creating a new Kotlin MPP project
- Configuring Gradle files for multiplatform support
- Setting up platform-specific and shared code modules
- Building and running your project
- Creating a simple cross-platform calculator application
Kotlin Multiplatform enables you to share business logic across different platforms while still allowing platform-specific implementations when necessary. This approach provides the best of both worlds: code sharing for efficiency and native implementation for optimal user experience.
Additional Resources
- Official Kotlin Multiplatform Documentation
- Kotlin Multiplatform Mobile Guide
- KMM Sample Projects on GitHub
- Kotlin Multiplatform Gradle Plugin
Exercises
- Extend the calculator example to include more advanced operations (power, square root, etc.)
- Create a simple to-do list application with shared data models and business logic
- Implement platform-specific storage solutions (Room for Android, CoreData for iOS) but with a common interface
- Add a web target to your multiplatform project using Kotlin/JS
- Implement unit tests for your shared code that run on all platforms
Happy coding with Kotlin Multiplatform!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)