Intermediate_source_sets

Intermediate source sets in Kotlin Multiplatform projects are shared source sets that are used to share code between a subset of targets rather than all of them. These source sets act as a middle layer between the common code (shared across all targets) and platform-specific code, allowing for reuse across some, but not all, of the supported platforms.

Key points about intermediate source sets:

  1. Sharing Code Across Some Targets: Intermediate source sets are designed to hold code that is shared between specific platforms. For example, you might have an iosMain source set that is shared between all iOS targets but not other platforms like Android or JVM.

  2. Customization for Specific Platforms: You can include platform-specific APIs or logic that apply to a subset of platforms (e.g., native platforms like iOS, macOS) while avoiding this code for others (like JVM or JS).

  3. Layer Between Common and Platform-Specific Code:

    • The common source set is shared across all targets.
    • Intermediate source sets are placed between the common source set and specific platform source sets.
    • Platform-specific source sets are at the bottom layer and contain code unique to that platform.

Example:

In a Kotlin Multiplatform project, you may define an intermediate source set for native targets (iOS and macOS) but exclude JVM and JS from sharing this code.

kotlin {
    jvm()
    ios()
    macosX64()

    sourceSets {
        val commonMain by getting
        val nativeMain by creating {  // Intermediate source set shared between iOS and macOS
            dependsOn(commonMain)
        }
        iosMain.get().dependsOn(nativeMain)
        macosX64Main.get().dependsOn(nativeMain)
    }
}

In this example:

  • commonMain is shared across all targets.
  • nativeMain is an intermediate source set shared by both iosMain and macosX64Main, but not by jvmMain.
  • Code placed in nativeMain can be used by both iOS and macOS, but not by JVM.

Why Use Intermediate Source Sets?

  1. Platform-Specific APIs: You can use APIs specific to a certain subset of platforms (like native iOS or macOS APIs) without polluting the code that gets compiled for other platforms like JVM or JS.
  2. Code Reuse: It reduces duplication by sharing common code between certain platforms.
  3. Flexibility: It gives you more granular control over code-sharing while respecting platform-specific constraints and APIs.

Example Structure:

In a project with ios and android targets, you might have these source sets:

  • commonMain (shared across all platforms)
  • iosMain (specific to iOS)
  • androidMain (specific to Android)
  • appleMain (intermediate source set, shared by iOS and macOS targets)

Backlinks