Kotlin Multiplatform: Sharing Code between Android, iOS, and the Web

In this article, we will take a look at Kotlin Multiplatform, a powerful feature that enables you to share code between Android, iOS, and the web. We will discuss the concepts of expect and actual declarations, walk through the process of setting up a multiplatform project, and demonstrate how to effectively use Kotlin Multiplatform with detailed explanations and code examples.

1. The Concepts of Expect and Actual Declarations

At the heart of Kotlin Multiplatform are expect and actual declarations. The expect keyword is used to define a common API that will be implemented on different platforms, while the actual keyword is used to provide platform-specific implementations of these APIs. Let's take a look at an example:

/* Shared Code */
expect class PlatformInfo {
    val platformName: String
}

/* Android Code */
actual class PlatformInfo {
    actual val platformName: String = "Android"
}

/* iOS Code */
actual class PlatformInfo {
    actual val platformName: String = "iOS"
}

In the shared code, we declare an expect class called PlatformInfo with a property platformName. In the Android and iOS code, we provide actual implementations of PlatformInfo with the platformName property set to the corresponding platform string.

2. Setting Up a Kotlin Multiplatform Project

To set up a Kotlin Multiplatform project, you need to follow these steps:

  1. Install the KMM Plugin: Install the Kotlin Multiplatform Mobile plugin in your IDE (IntelliJ IDEA or Android Studio) by following the official installation guide.
  2. Create a KMM Project: Create a new KMM project using the provided project wizard. This will generate a project structure with separate source sets for shared, Android, and iOS code.
  3. Configure build.gradle.kts: Configure the build.gradle.kts files in your project to define the source sets and dependencies for each platform. Here is a basic example:
// build.gradle.kts (Project Level)
plugins {
    kotlin("multiplatform") version "1.6.0"
}

kotlin {
    android()
    ios()

    sourceSets {
        val commonMain by getting {
            dependencies {
                implementation("org.jetbrains.kotlin:kotlin-stdlib-common")
            }
        }

        val androidMain by getting {
            dependencies {
                implementation("org.jetbrains.kotlin:kotlin-stdlib")
            }
        }

        val iosMain by getting {
            dependencies {
                implementation("org.jetbrains.kotlin:kotlin-stdlib")
            }
        }
    }
}

This example configures the Kotlin Multiplatform plugin and sets up the source sets for common, Android, and iOS platforms. It also adds the required dependencies for each platform.

3. Writing and Sharing Code

With your project set up, you can now write and share code between platforms. Let's extend the previous example to demonstrate how to use the shared PlatformInfo class:

/* Shared Code */
expect class PlatformInfo {
    val platformName: String
}

fun printPlatformInfo() {
    val info = PlatformInfo()
    println("Running on ${info.platformName}")
}

/* Android Code */
actual class PlatformInfo {
    actual val platformName: String = "Android"
}

/* iOS Code */
actual class PlatformInfo {
    actual val platformName: String = "iOS"
}

In the shared code, we create a function called printPlatformInfo that uses the PlatformInfo class. This function can be called from both the Android and iOS platforms, and it will print the correct platform name based on the actual implementation provided for each platform.

4. Integrating with Platform Projects

Now that we have shared code, we need to integrate it with our platform-specific projects. Here's how you can call the shared printPlatformInfo function from an Android Activity and an iOS ViewController:

// Android (MainActivity.kt)
import com.example.shared.printPlatformInfo

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        printPlatformInfo()
    }
}

// iOS (ViewController.swift)
import SharedCode

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

        printPlatformInfo()
    }
}

By importing the shared code, we can call the printPlatformInfo function from both Android and iOS projects. When executed, the function will print "Running on Android" for the Android app and "Running on iOS" for the iOS app.

Conclusion

Kotlin Multiplatform enables you to effectively share code between Android, iOS, and the web, simplifying the development process and making your codebase more maintainable. By understanding the concepts of expect and actual declarations, properly setting up a multiplatform project, and effectively using Kotlin Multiplatform, you can create robust, efficient, and maintainable cross-platform applications.

Table of Contents

  1. Introduction to Kotlin: A Powerful and Concise Programming Language with Key Differences from Java
  2. Kotlin Syntax Basics: Understanding Variables, Functions, and Control Structures
  3. Kotlin Object-Oriented Programming: Classes, Inheritance, and Interfaces
  4. Kotlin Functional Programming: Lambdas, Collections, and Extension Functions
  5. Kotlin Coroutines: Simplifying Asynchronous Programming
  6. Kotlin for Android Development: Building Your First Android App with Kotlin
  7. Kotlin DSL: Creating Domain-Specific Languages with Kotlin
  8. Kotlin Multiplatform: Sharing Code between Android, iOS, and the Web
  9. Kotlin Best Practices: Writing Clean and Efficient Kotlin Code
  10. Kotlin Resources: Books, Online Courses, and Communities to Learn More About Kotlin