I am converting an Android app to the Gradle Kotlin-DSL by using Kotlinscript files.
I have a problem converting our applicationId logic. We don't use the defaultConfiguration with applicationId plus various applicationIdSuffix for our flavors but a custom logic. The logic is described in this SO answer, here is the groovy code:
flavorDimensions "price", "dataset"
productFlavors {
free { dimension "price" }
paid { dimension "price" }
dataset1 { dimension "dataset" }
dataset2 { dimension "dataset" }
}
android.applicationVariants.all { variant ->
def mergedFlavor = variant.mergedFlavor
switch (variant.flavorName) {
case "freeDataset1":
mergedFlavor.setApplicationId("com.beansys.freeappdataset1")
break
case "freeDataset2":
mergedFlavor.setApplicationId("com.beansys.freedataset2")
break
case "paidDataset1":
mergedFlavor.setApplicationId("com.beansys.dataset1paid")
break
case "paidDataset2":
mergedFlavor.setApplicationId("com.beansys.mypaiddataset2")
break
}
}
With kotlin I cannot alter the applicationId of the mergedFlavor like in groovy. It is a val and therefore can't be changed.
Any elegant solution to solve this?
Google added the variants API with the Android Gradle Plugin 7.0.0. With it we can alter the applicationId.
android {
flavorDimensions.addAll(listOf("price", "dataset"))
productFlavors {
create("free") { dimension = "price" }
create("pro") { dimension = "price" }
create("dataset1") { dimension = "dataset" }
create("dataset2") { dimension = "dataset" }
}
}
androidComponents {
onVariants { variant ->
val applicationId = when(variant.flavorName) {
"freeDataset1" -> "com.beansys.freeappdataset1"
"freeDataset2" -> "com.beansys.freedataset2"
"proDataset1" -> "com.beansys.dataset1paid"
"proDataset2" -> "com.beansys.mypaiddataset2"
else -> throw(IllegalStateException("Whats your flavor? ${variant.flavorName}!"))
}
variant.applicationId.set(applicationId)
}
}
Note that it is probably better to use a task to determine the applicationId.
For more informations see the following resources:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With