简体   繁体   中英

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 初始值设定项应该是一个常量值

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?

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'
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM