我不能使用BuildConfig.DEBUG

时间:2018-05-13 12:32:56

标签: kotlin buildconfig

当我使用

BuildConfig.DEBUG

在Kotlin我收到此错误:

expecting member declaratuon

我的代码:

class API {

    companion object {
        private lateinit var instance: Retrofit
        private const val baseUrl = baseURL

        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
            builder.addInterceptor(interceptor);
        }

}

2 个答案:

答案 0 :(得分:3)

你不能将if语句用作这样的顶级声明,你必须在函数或init块中声明它。

这样的事情,或许是:

class API {

    companion object {
        private lateinit var instance: Retrofit
        private const val baseUrl = baseURL

        init {
            if (BuildConfig.DEBUG) {
                HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
                builder.addInterceptor(interceptor);
            }
        }
    }
}

答案 1 :(得分:3)

您正在函数或构造函数外部进行调用。你不能在方法体之外使用if语句,它适用于Kotlin和Java。

double也是类,尽管它们都遵循单例模式。你仍然不能将if语句放在方法体外。类级声明只能包含方法,构造函数和字段,以及一些块(即object),而不是if语句和对已定义变量的调用。

此外,您使用的Java语法根本无法编译。请改用Kotlin语法并将其移动到伴随对象内的init块。

初始化伴随对象时,初始化块被称为初始化。

init