-1

当我使用

BuildConfig.DEBUG

在科特林我得到这个错误:

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);
        }

}
4

2 回答 2

4

您不能将 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);
            }
        }
    }
}
于 2018-05-13T12:42:27.170 回答
2

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

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

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

初始化伴随对象时,init 块的调用方式与初始化类似。

companion object{
    //Other declarations

    init{
        if (BuildConfig.DEBUG) {
            var interceptor = HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
            builder.addInterceptor(interceptor);//I have no clue where you define builder, but I'm assuming you've done it *somewhere* and just left it out of the question
        }
    }
}
于 2018-05-13T12:42:52.673 回答