This tutorial aims to guide you on how to share code between Android and iOS platforms using Kotlin Multiplatform. By the end of this tutorial, you will be able to build a sample project that shares common logic and features between Android and iOS.
What will you learn?
- Basics of Kotlin Multiplatform
- Creating a shared module
- Writing shared code
- Integrating shared code into Android and iOS apps
Prerequisites
- Basic knowledge of Android and iOS development
- A working installation of Android Studio and Xcode
- Basic understanding of Kotlin and Swift
Kotlin Multiplatform Mobile (KMM) is a feature of Kotlin that allows you to write code once and compile it for both Android (JVM) and iOS (Native). A KMM module consists of common, Android, and iOS parts. The common part contains shared logic, while platform-specific parts contain implementations of expected features or APIs.
Shared code resides in the commonMain
directory of the shared module. This code can be used both by Android and iOS platforms.
// commonMain/kotlin/sample/Sample.kt
package sample
expect class Sample() {
fun checkMe(): Int
}
fun hello(): String = "Hello from common module"
In this sample, hello()
function is shared code that can be accessed from both Android and iOS. Sample
is an expect class, which means its actual implementation will be provided by each platform.
The actual implementations of expect classes are provided in the androidMain
and iosMain
directories.
// androidMain/kotlin/sample/Sample.kt
package sample
actual class Sample {
actual fun checkMe() = 42
}
// iosMain/kotlin/sample/Sample.kt
package sample
actual class Sample {
actual fun checkMe() = 7
}
In Android app, the Sample().checkMe()
will return 42
, while in iOS app, it will return 7
.
Now, you can call the shared code from your Android and iOS apps.
// MainActivity.kt
import sample.hello
import sample.Sample
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<TextView>(R.id.textView).text = "${hello()}, ${Sample().checkMe()}"
}
}
// ViewController.swift
import SharedCode
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
label.text = "\(Sample().checkMe()), \(hello())"
}
@IBOutlet weak var label: UILabel!
}
In this tutorial, you learned how to share code between Android and iOS using Kotlin Multiplatform. You created a shared module, wrote shared code, and integrated it into Android and iOS apps.
Next steps:
- Explore more features of KMM
- Try sharing more complex features or libraries
Additional resources:
- Kotlin Multiplatform Documentation
- KMM Sample Projects on GitHub
Tips for further practice:
- Try sharing UI components using Kotlin Multiplatform.
- Explore how to handle platform-specific APIs in shared code.