You Qi
You Qi

Reputation: 9231

is BuildConfig.DEBUG a compile-time constant?

I'm trying to create a ProductionRelease compile-time constant, so that R8 can omit our debugging codes in the final production apk. I hit a roadblock whereby the BuildConfig.DEBUG is not assignable to a const val.

// MyApplication.kt

companion object {
        const val isDebug = BuildConfig.DEBUG
        const val isProductionRelease = BuildConfig.FLAVOR == "production" && !BuildConfig.DEBUG
}

const val initializer should be a constant value

Upon further checking, I found out BuildConfig.DEBUG is wrapped with a Boolean.parseBoolean() wrapper.

// BuildConfig.java

/**
 * Automatically generated file. DO NOT MODIFY
 */

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "com...";
  ...
}

Questions here is:

  1. Why can't I assign a static final boolean to a const val?
  2. Why BuildConfig.DEBUG can't be generated using true|false directly but have to parse through a parseBoolean function?

Upvotes: 2

Views: 1274

Answers (1)

galcyurio
galcyurio

Reputation: 1855

Why can't I assign a static final boolean to a const val?

static final variable is not initialized at compile time. So we cannot assign uninitialized value to const val.

  1. Why BuildConfig.DEBUG can't be generated using true|false directly but have to parse through a parseBoolean function?

Boolean literals inside the BuildConfig class are going to produce IDE warnings when using them in your code (at least within Android Studio). You can see more details in this link.


Instead of DEBUG, you can use BUILD_TYPE.

const val isDebug = BuildConfig.BUILD_TYPE == "debug"
const val isProductionRelease = BuildConfig.FLAVOR == "production" && !isDebug

Or you can also add new constants as boolean literals in BuildConfig.

buildTypes {
    debug {
        buildConfigField 'boolean', 'DEBUG_CONST', 'true'
    }
    release {
        buildConfigField 'boolean', 'DEBUG_CONST', 'false'
    }
}

Upvotes: 4

Related Questions