Kotlin Multi Platform Project Setup
Kotlin Multi Platform uses Gradle as a build tool. Using the Kotlin Multi Platform Gradle Plugin makes defining such projects and their dependencies very easy.
plugins {
id 'org.jetbrains.kotlin.multiplatform'
}
kotlin {
jvm()
iosX64 {
binaries {
framework()
}
}
sourceSets {
commonMain {
dependencies {
implementation kotlin('stdlib-common')
}
}
jvmMain {
dependencies {
implementation kotlin('stdlib')
}
}
}
}
In fact, we only need to specify the target platforms which we want to support (in our case iOS and Android) and the libraries we want to use (in our case the Kotlin Standard Library) as dependencies.
We keep the Android, and the iOS project in the same directory as the multi platform project.
Now lets implement the common business logic using Kotlin.
fun add(inputA: String, inputB: String): String {
val numberA = inputA.toDoubleOrNull() ?: 0.0
val numberB = inputB.toDoubleOrNull() ?: 0.0
val resultValue = numberA + numberB
return "The result (from common) is: $resultValue"
}
After that we can compile this code, using ./gradlew build
, to an iOS library
which can be used inside of the Xcode project.
Finally, we can call our new Kotlin function from iOS
Button(action: {
self.result = CalculatorKt.add(
inputA: self.inputA,
inputB: self.inputB)
}) {
Text("Calculate")
}
.padding(.bottom)
HStack {
Text(self.result)
}
Integrating the new function into the Android project is even easier. Both projects use Gradle as their build system. So it´s only a matter of defining a dependency in the Android project in order to be able to use our new Kotlin lib.
dependencies {
implementation project(':kotlin-mpp-common')
...
}
Then we use the new function in the Android project.
calculateButton.setOnClickListener {
result.text = add(inputA.text.toString(), inputB.text.toString())
}