Why using BuildConfig.DEBUG
inside companion object
cause expecting member declaratuon
Error?
code:
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)
}
}
You're making a call outside a function or constructor. You cannot have if-statements outside method bodies, which applies to both Kotlin and Java.
object
s are classes too, all though they follow the singleton pattern. You still can't put if-statements outside method bodies. The class-level declarations can only contain methods, constructors, and fields, and some blocks (i.e. init
), not if-statements and calls to the defined variables.
In addition, you're using Java syntax which won't compile at all. Use Kotlin syntax instead and move it to an init block inside the companion object.
The init block is called like initialization when the companion object is initialized.
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
}
}
}