Maintaining separate Android and iOS applications often means implementing the same business rules twice. An Android application may use Kotlin while its iOS counterpart uses Swift. Although both applications communicate with the same backend, developers still need to maintain separate implementations for authentication, data validation, API communication, caching, and other application logic.
Consider a banking application that supports Android and iOS. Both applications need to validate payment details, calculate transaction fees, retrieve account information, and apply the same transaction rules.
If these rules are implemented independently, a change made to the Android application may not be reflected correctly in the iOS application. Over time, the two implementations can behave differently even though they are supposed to follow the same business requirements.
Kotlin Multiplatform (KMP) provides a way to share selected application code across platforms without requiring developers to replace their existing native applications.
Android can continue using Kotlin and its native Android framework, while iOS can continue using Swift and SwiftUI. Both applications can call a shared Kotlin module containing common business logic.
This approach is particularly useful for teams that want to reduce duplicated code while preserving native user interfaces and platform-specific capabilities.
This article explains how Kotlin Multiplatform works, how to organize a shared module, how to implement reusable business logic, and how to integrate that module into Android and iOS applications.
Understanding Kotlin Multiplatform
Kotlin Multiplatform allows developers to share Kotlin code across different platforms, including Android, iOS, desktop, web, and server environments.
The important point is that KMP does not require every part of an application to be shared.
Developers decide which functionality belongs in common code and which functionality should remain platform-specific.
For example, consider a mobile application with the following components:
Application component | Recommended implementation |
|---|
Business rules | Shared Kotlin |
Data models | Shared Kotlin |
API communication | Shared Kotlin |
Data validation | Shared Kotlin |
Authentication workflows | Shared Kotlin where appropriate |
Android user interface | Kotlin with Jetpack Compose or Views |
iOS user interface | SwiftUI or UIKit |
Push notifications | Native platform implementation |
Camera integration | Native platform implementation |
Platform permissions | Native platform implementation |
This separation allows both applications to reuse the same business rules while retaining their own user experience.
Kotlin Multiplatform uses Kotlin Multiplatform Gradle configuration to define supported targets and source sets. Shared code is placed in common source sets, while platform-specific implementations are placed in their respective source sets.
For iOS, Kotlin code is compiled using Kotlin/Native and exposed through a framework that the iOS application can integrate.
The result is not a requirement to rewrite the entire application. It is a shared code layer that can be introduced gradually.
Designing the Shared Module
A good starting point is to create a separate shared module that contains business logic independent of Android and iOS user-interface frameworks.
For example, an application might use the following project structure:
MobileApplication/
|
|-- androidApp/
| |-- src/
| |-- build.gradle.kts
|
|-- iosApp/
| |-- ContentView.swift
| |-- AppDelegate.swift
|
|-- shared/
| |-- src/
| |-- commonMain/
| | |-- kotlin/
| | |-- model/
| | |-- repository/
| | |-- validation/
| | |-- service/
| |
| |-- commonTest/
| | |-- kotlin/
| |
| |-- androidMain/
| | |-- kotlin/
| |
| |-- iosMain/
| |-- kotlin/
The commonMain source set contains code that can be compiled for all configured targets.
The commonTest source set contains tests for shared functionality.
The androidMain source set contains Android-specific implementations, while iosMain contains implementations for Apple platforms.
This structure makes responsibilities clear. A payment validation rule should normally be placed in commonMain because both applications need the same behavior. An Android-specific permission request should remain in the Android application or Android-specific source set.
Avoid moving platform-dependent code into the shared module simply to increase the percentage of shared code. The objective is to reuse logic that genuinely has the same behavior across platforms.
Configure the Kotlin Multiplatform Module
A Kotlin Multiplatform project uses Gradle to configure its targets, source sets, and dependencies.
A simplified shared module configuration looks like this:
plugins {
kotlin("multiplatform")
}
kotlin {
androidTarget()
iosArm64()
iosSimulatorArm64()
targets.withType<
org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget
>().configureEach {
binaries.framework {
baseName = "Shared"
isStatic = true
}
}
sourceSets {
commonMain.dependencies {
// Add dependencies supported by common code.
}
commonTest.dependencies {
implementation(kotlin("test"))
}
}
}
This example demonstrates the important parts of a multiplatform configuration.
The androidTarget declaration configures an Android target. The iosArm64 target supports physical Apple devices using ARM64 architecture, while iosSimulatorArm64 supports Apple Silicon simulators.
The framework configuration creates an Apple framework named Shared. The iOS application can then integrate this framework and import its exported Kotlin APIs.
The exact Android Gradle plugin setup depends on the Android application and library configuration used by the project. Modern Kotlin Multiplatform projects can use the dedicated Android library integration where appropriate.
For a real application, also configure the required SDK versions, Gradle plugins, framework settings, and supported deployment targets.
The example is a starting point rather than a complete production build configuration.
Implement Shared Business Logic
Consider a payment application that needs to validate transaction amounts before submitting a request to the backend.
Both Android and iOS applications must apply the same rules:
The amount must be greater than zero.
The amount cannot exceed the permitted transaction limit.
The amount must contain no more than two decimal places.
Instead of implementing these rules separately, place them in commonMain.
Create a file named PaymentValidator.kt:
package com.example.shared.validation
sealed class PaymentValidationResult {
data object Valid : PaymentValidationResult()
data object InvalidAmount : PaymentValidationResult()
data object AmountExceedsLimit :
PaymentValidationResult()
data object InvalidPrecision :
PaymentValidationResult()
}
class PaymentValidator {
fun validate(
amount: Double,
maximumLimit: Double
): PaymentValidationResult {
if (!amount.isFinite() || !maximumLimit.isFinite()) {
return PaymentValidationResult.InvalidAmount
}
if (amount <= 0 || maximumLimit <= 0) {
return PaymentValidationResult.InvalidAmount
}
if (amount > maximumLimit) {
return PaymentValidationResult.AmountExceedsLimit
}
val normalized = amount.toBigDecimal()
.stripTrailingZeros()
if (normalized.scale() > 2) {
return PaymentValidationResult.InvalidPrecision
}
return PaymentValidationResult.Valid
}
}
This implementation places the validation rules in one location.
The Android application and iOS application can both use PaymentValidator instead of maintaining separate validation implementations.
For financial applications, production code should use an appropriate decimal representation for monetary values rather than relying on binary floating-point values such as Double. The example keeps the focus on sharing business rules; a real payment model should define currency precision and rounding behavior explicitly.
The important architectural decision is that the validation rules are shared, while the way each application displays validation errors remains native.
Use Shared Models Across Platforms
Data models are another good candidate for shared code.
For example, both applications may need to display transaction information returned by an API.
Create a shared model:
package com.example.shared.model
data class Transaction(
val transactionId: String,
val amount: Double,
val currency: String,
val status: String
)
The Android application can use this model directly from Kotlin.
The iOS application can access the exported Kotlin framework and consume the model through its generated interoperability interface.
This avoids maintaining separate model definitions for the same business entity.
However, developers should consider how Kotlin types are exposed to Swift. Kotlin classes, collections, nullable values, and sealed types may appear differently in the generated framework interface.
For a stable iOS integration, keep the public shared API straightforward. Avoid exposing a large internal object graph directly to Swift. A small set of clearly designed public classes and methods is easier to maintain.
Share Networking and Repository Logic
Networking is another area where shared code can reduce duplication.
Suppose both applications call the same backend endpoint to retrieve account transactions.
Without shared networking, Android and iOS may each implement their own API client, response parsing, error mapping, and retry rules.
A shared repository can centralize these responsibilities.
For example, the following interface defines the expected behavior:
package com.example.shared.repository
import com.example.shared.model.Transaction
interface TransactionRepository {
suspend fun getTransactions(
accountId: String
): List<Transaction>
}
A concrete implementation can use a multiplatform networking library such as Ktor.
A simplified implementation might look like this:
package com.example.shared.repository
import com.example.shared.model.Transaction
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
class DefaultTransactionRepository(
private val client: HttpClient,
private val baseUrl: String
) : TransactionRepository {
override suspend fun getTransactions(
accountId: String
): List<Transaction> {
return client.get(
"$baseUrl/accounts/$accountId/transactions"
).body()
}
}
This example assumes that the Ktor client is configured with the required serialization support and that the API response can be deserialized into Transaction objects.
The same repository implementation can be used by both mobile applications.
In a production application, the repository should also handle authentication, request timeouts, network failures, API error responses, and cancellation.
Avoid placing access tokens or other sensitive credentials directly inside shared source code. Use an appropriate platform-backed secure storage implementation and pass the required credentials into the shared networking layer through a controlled interface.
Handle Platform-Specific APIs With expect and actual
Some application functionality cannot be implemented identically on every platform.
For example, an application may need to retrieve the current device name or access a platform-specific service.
Kotlin Multiplatform supports expect and actual declarations for this purpose.
The common source set declares what functionality is expected, while each platform provides its own implementation.
For example, create a file named PlatformInfo.kt in commonMain:
package com.example.shared
expect class PlatformInfo() {
fun getPlatformName(): String
}
Then implement the declaration in androidMain:
package com.example.shared
actual class PlatformInfo {
actual fun getPlatformName(): String {
return "Android"
}
}
Create the corresponding implementation in iosMain:
package com.example.shared
import platform.UIKit.UIDevice
actual class PlatformInfo {
actual fun getPlatformName(): String {
return UIDevice.currentDevice.systemName
}
}
The shared application code can call PlatformInfo without knowing which platform implementation is being used.
When the Android application runs, the Android implementation is used. When the iOS application runs, the iOS implementation is used.
This mechanism is useful for platform-specific behavior that needs a common interface.
However, expect and actual should not become a way to move every platform feature into the shared module. Large platform-specific APIs are often easier to maintain in native application code behind a well-defined interface.
Integrate the Shared Module With an iOS Application
Android can normally depend on the shared Kotlin module as part of the Gradle project.
iOS requires an additional integration step because Swift cannot directly import a Kotlin source module.
Kotlin Multiplatform generates a native framework that the iOS application can use.
In the shared module, configure an iOS framework:
listOf(
iosArm64(),
iosSimulatorArm64()
).forEach { target ->
target.binaries.framework {
baseName = "Shared"
isStatic = true
}
}
For local development, Kotlin Multiplatform supports direct integration with Xcode.
The integration uses the Gradle task embedAndSignAppleFrameworkForXcode. A Run Script build phase in the Xcode project invokes this task so that the framework is built and embedded as part of the iOS build.
A simplified script looks like this:
if [ "YES" = "$OVERRIDE_KOTLIN_BUILD_IDE_SUPPORTED" ]; then
exit 0
fi
cd "$SRCROOT/.."
./gradlew :shared:embedAndSignAppleFrameworkForXcode
The path should point to the root of the multiplatform project, and shared should match the actual shared module name.
After configuring the framework integration, the Swift application can import the generated module:
import Shared
The iOS application can then use the exported Kotlin classes.
For example, if PaymentValidator is exported through the framework, the generated Swift interface can be used to create and call it. The exact names and signatures should be checked in Xcode's generated framework interface because Kotlin types are exposed through Objective-C interoperability.
For teams that prefer dependency-based distribution, the framework can also be published and integrated as a remote dependency. The appropriate method depends on whether the Android and iOS applications are maintained in the same repository and how the team manages native dependencies.
Call Shared Asynchronous Logic From Swift
Shared networking code often uses Kotlin coroutines and suspend functions.
Android can call these functions naturally from Kotlin coroutine scopes. Swift requires additional interoperability work because Kotlin suspend functions are not automatically presented as ordinary Swift async functions in every integration setup.
For example, a shared repository may expose:
suspend fun getTransactions(
accountId: String
): List<Transaction>
The iOS application needs a suitable bridge to call this function and receive the result asynchronously.
Common approaches include using a library such as KMP-NativeCoroutines or creating a dedicated Swift-facing API layer.
The iOS application can then expose the operation through Swift concurrency:
func loadTransactions() async {
do {
let transactions = try await viewModel.fetchTransactions()
// Update SwiftUI state with the result.
} catch {
// Handle the error.
}
}
The example represents the desired Swift-facing API, not a direct call to every Kotlin suspend function. The implementation of fetchTransactions depends on the selected interoperability approach.
When designing the shared API, consider cancellation, error conversion, and object lifetime. A network request should not continue unnecessarily after the user leaves the screen.
Keep the User Interface Native
Kotlin Multiplatform does not require developers to share the user interface.
A practical architecture can keep Jetpack Compose or Android Views on Android and SwiftUI or UIKit on iOS.
Both applications call the same shared repository and business logic.
For example:
<CodeBlock language="mermaid" id="59275"> flowchart TB A["Android Application"] --> B["Shared Kotlin Module"] C["iOS Application"] --> B A --> D["Jetpack Compose / Android Views"] C --> E["SwiftUI / UIKit"] B --> F["Business Logic"] B --> G["Networking"] B --> H["Data Models"] B --> I["Validation and Repository Logic"] G --> J["Backend APIs"] </CodeBlock>
This approach is useful when platform-specific user experience is important.
Android and iOS can have different navigation patterns, animations, layouts, and accessibility behavior while sharing the same underlying rules.
If the project needs more UI reuse, Compose Multiplatform can also be considered. It allows developers to share UI code across supported platforms while still integrating platform-specific APIs.
However, sharing the UI is a separate architectural decision. Teams should evaluate it based on design requirements, native integration needs, and maintenance considerations rather than assuming that every KMP project should use a shared interface.
Test Shared Code Independently
One of the major advantages of moving business logic into a shared module is that it becomes easier to test the same rules for multiple platforms.
The commonTest source set can contain tests that validate shared behavior.
For example:
import kotlin.test.Test
import kotlin.test.assertEquals
class PaymentValidatorTest {
private val validator = PaymentValidator()
@Test
fun shouldRejectNegativeAmount() {
val result = validator.validate(
amount = -100.0,
maximumLimit = 10000.0
)
assertEquals(
PaymentValidationResult.InvalidAmount,
result
)
}
@Test
fun shouldRejectAmountAboveLimit() {
val result = validator.validate(
amount = 15000.0,
maximumLimit = 10000.0
)
assertEquals(
PaymentValidationResult.AmountExceedsLimit,
result
)
}
@Test
fun shouldAcceptValidAmount() {
val result = validator.validate(
amount = 250.50,
maximumLimit = 10000.0
)
assertEquals(
PaymentValidationResult.Valid,
result
)
}
}
These tests verify the shared validation behavior independently of the Android and iOS user interfaces.
The shared module should also be tested on the relevant targets. A test that passes on the JVM does not automatically prove that every native target behaves correctly.
In addition, platform-specific integration tests should verify framework interoperability, API communication, secure storage, and other operating-system features.
Common Mistakes When Adopting Kotlin Multiplatform
Kotlin Multiplatform reduces duplication, but it introduces architectural and build considerations that teams must understand.
One common mistake is trying to move the entire existing application into the shared module immediately. This often creates unnecessary complexity, particularly when the applications depend heavily on native frameworks.
Another mistake is putting Android-specific dependencies into commonMain. Shared source sets can only use APIs and libraries supported by the configured targets.
Developers should also avoid exposing every internal Kotlin class directly to Swift. A small, stable public API makes iOS integration easier and reduces interoperability problems.
Build configuration requires attention as well. The Kotlin framework must be generated for the correct Apple architectures and integrated consistently with the Xcode build.
Finally, teams should not assume that sharing business logic removes the need for native testing. Platform-specific permissions, lifecycle behavior, notifications, and user-interface interactions still require testing on their respective platforms.
Conclusion
Kotlin Multiplatform provides a flexible way to share application logic between Android and iOS without requiring teams to abandon their existing native development approach.
Developers can place business rules, data models, networking, validation, and repository logic in a shared Kotlin module. Android can use that module directly, while iOS can consume the generated native framework through Swift interoperability.
The most practical adoption strategy is to begin with a small, well-defined part of the application. Shared validation, API models, or repository logic are good starting points because they have clear boundaries and can be tested independently.
Keep platform-specific user interfaces and operating-system integrations native when they provide value. Introduce shared UI only when the project benefits from it.
The goal is not to maximize the amount of shared code. It is to maintain consistent business behavior across platforms while keeping the application architecture understandable, testable, and easy to evolve.
Join the conversation! Your thoughts help the community grow.