Is there anyway we can create flavored versions of Kotlin Multiplatform build files like dev and prod?
Asked Answered
H

1

25

I have a requirement where I want to have different set of data to be shipped with the library generated by kotlin multiplatform module for different flavors like dev and prod. In an Android project, we can do with productFlavors in the app's build.gradle.

Is there any similar way of doing the same in Kotlin Multiplatform?

Holst answered 16/1, 2020 at 9:24 Comment(1)
There are two build types available for Kotlin/Native targets, see here. Maybe something can be done using this plugin. Also, I've seen a discussion on that in the Kotlin's Slack.Bindman
R
0

Define different source sets for different flavors, such as dev and prod, in the platform-specific modules (e.g., androidMainDev, androidMainProd).

// Common module
    expect class DataManager {
        fun fetchData(): String
    }
    
    // Android platform module
    class AndroidDevDataManager : DataManager {
        override fun fetchData(): String {
            return "Data for development"
        }
    }
    
    class AndroidProdDataManager : DataManager {
        override fun fetchData(): String {
            return "Data for production"
        }
    }

In this example, DataManager is an interface declared in the common module using an expect keyword. Platform-specific implementations are provided in the Android platform module using the actual keyword.

Then, in your Android project, you can configure different source sets for dev and prod flavors in the build.gradle.kts:

kotlin {
    android {
        // Configuration for dev flavor
        sourceSets {
            named("androidMainDev") {
                kotlin.srcDirs("src/androidMainDev/kotlin")
            }
        }
        
        // Configuration for prod flavor
        sourceSets {
            named("androidMainProd") {
                kotlin.srcDirs("src/androidMainProd/kotlin")
            }
        }
    }
}
Rogerson answered 24/4, 2024 at 9:17 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.