Kotlin / Kotlin Multiplatform Development

Sharing Code Between Android and iOS

This tutorial focuses on how to share code between Android and iOS platforms using Kotlin Multiplatform.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Introduces Kotlin Multiplatform for building cross-platform applications.

Introduction

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

Step-by-Step Guide

Kotlin Multiplatform

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.

Creating a Shared Module

  1. In Android Studio, create a new project and select the "KMM Application" template.
  2. Name your project and click "Finish". Android Studio creates a project with a shared module and sample Android and iOS apps.

Writing Shared Code

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.

Integrating Shared Code

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.

Code Examples

Now, you can call the shared code from your Android and iOS apps.

Android

// 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()}"
    }
}

iOS

// ViewController.swift

import SharedCode

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = "\(Sample().checkMe()), \(hello())"
    }

    @IBOutlet weak var label: UILabel!
}

Summary

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

Practice Exercises

  1. Create a shared function that returns the current date as a string.
  2. Implement a shared class that calculates the factorial of a number.
  3. Share a more complex feature, such as network requests or database access.

Tips for further practice:
- Try sharing UI components using Kotlin Multiplatform.
- Explore how to handle platform-specific APIs in shared code.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Scientific Calculator

Perform advanced math operations.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Favicon Generator

Create favicons from images.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help