Kotlin Multiplatform Android — Complete Guide
In this tutorial, you'll learn about Kotlin Multiplatform Android. We cover key concepts, practical examples, and best practices.
The Problem
Your KMP shared module can't use Android-specific APIs, or the Android source set doesn't have the right dependencies.
Wrong Approach ❌
// Putting Android Context in commonMain
// commonMain
class MyRepository(context: Context) { // Context doesn't exist in commonMain!
// ...
}
Output: Compilation error: Unresolved reference: Context in commonMain.
Right Approach ✅
// build.gradle.kts — shared module
kotlin {
androidTarget()
sourceSets {
val androidMain by getting {
dependencies {
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.7.0")
implementation("androidx.room:room-runtime:2.6.1")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.0")
}
}
val commonMain by getting {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.0")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.3")
}
}
}
}
// commonMain
expect class PlatformContext
expect class DatabaseFactory {
fun createDatabase(): Database
}
// androidMain
actual typealias PlatformContext = android.content.Context
actual class DatabaseFactory(private val context: PlatformContext) {
actual fun createDatabase(): Database {
val db = Room.databaseBuilder(
context,
AppDatabase::class.java, "shared-db"
).build()
return AndroidDatabase(db)
}
}
// Using in Android app
class MainActivity : AppCompatActivity() {
private val factory = DatabaseFactory(this)
private val db = factory.createDatabase()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// db is ready
}
}
Output: Shared module compiles for Android with proper platform code separation.
Prevention
- Use
expect/actualfor Android-specific types likeContext. - Keep Android dependencies in
androidMainsource set. - Use
androidTarget()(notandroid()which is deprecated). - Configure
compileSdk,minSdk, andtargetSdkin theandroidblock.
Common Mistakes with multiplatform android
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world KOTLIN code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro