LoginSignup
0
0

More than 3 years have passed since last update.

Android Flavor wrapper object

Last updated at Posted at 2019-06-26

When using multiple flavors in a single Android project, a wrapper such as below is a useful utility when checking the current flavor (e.g. when assigning different features to different flavor).

It is not recommended to check the BuildConfig.Flavor string manually outside of this wrapper, due to potential errors in the string equality. Instead, we only need to ensure the "Name" enum in this wrapper is correct, to ensure correctness throughout the project.

The example here assumes two flavors in the build.gradle: "euro" and "japan"

object Flavor {

    // NOTE: must match flavor/dimension names given in build.gradle
    enum class Name {
        euro,
        asia
    }

    val current: Name 
    get() {
        Name.values().firstOrNull { it.name.equals(BuildConfig.FLAVOR) }?.let{ name->
            return name
        } ?: run {
            throw Exception("Unknown flavor: " + BuildConfig.FLAVOR)
        }
    }

    val isEuro: Boolean = current.equals(Name.euro)
    val isAsia: Boolean = current.equals(Name.asia)
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0