Getting Started
We start by implementing a simple calculator app in Android and iOS
Android
On Android, we use a standard project with a single Activity.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
calculateButton.setOnClickListener {
val numberA = inputA.text.toString().toDoubleOrNull() ?: 0.0
val numberB = inputB.text.toString().toDoubleOrNull() ?: 0.0
val resultValue = numberA + numberB
result.text = "Result: ${resultValue}"
}
}
}
On iOS we use Xcode and Swift UI to implement the same calculator
struct ContentView: View {
@State private var inputA = ""
@State private var inputB = ""
@State private var result = 0.0
var body: some View {
VStack {
HStack {
TextField("Number A", text: $inputA)
.padding([.leading, .bottom])
.keyboardType(.numberPad)
}
HStack {
TextField("Number B", text: $inputB)
.padding([.leading, .bottom])
.keyboardType(.numberPad)
}
Button(action: {
let numberA = Double(self.inputA) ?? 0.0
let numberB = Double(self.inputB) ?? 0.0
self.result = numberA + numberB
}) {
Text("Calculate")
}
.padding(.bottom)
HStack {
Text("Result: \(self.result)")
}
}
}
}
Comparing the “Business Logic” of both implementations we see that they are in fact quite similar, and it would be great to have them in one place only.
val numberA = inputA.text.toString().toDoubleOrNull() ?: 0.0
val numberB = inputB.text.toString().toDoubleOrNull() ?: 0.0
val resultValue = numberA + numberB
result.text = "Result: ${resultValue}"
let numberA = Double(self.inputA) ?? 0.0
let numberB = Double(self.inputB) ?? 0.0
self.result = numberA + numberB
So let’s try to set up a Kotlin Multi Platform project and refactor that part into a common Kotlin library.