I have the following code:
abstract class Database : RoomDatabase() {
companion object {
@Volatile
lateinit var INSTANCE: Database
private set
fun init(context: Context) {
val initialized = ::INSTANCE.isInitialized
if (!initialized) {
INSTANCE = Room.databaseBuilder(...
which compiles just fine for some reason. At run-time, when the application started on device this exception is thrown:
java.lang.NoSuchFieldError: No static field INSTANCE of type Lpersistance/Database; in class Lpersistance/Database$Companion; or its superclasses (declaration of 'persistance.Database$Companion' appears in /data/app/split_lib_slice_1_apk.apk) at persistance.Database$Companion.init(Database.kt:22)
Checking decompiled version of the class, I found that INSTANCE
variable defined in Database class:
public abstract class Database extends RoomDatabase {
private static volatile Database INSTANCE;
.IsInitialised
code actually represented in Java version that way:
public static final class Companion {
public final Database getINSTANCE() {
return Database.access$getINSTANCE$cp();
}
private final void setINSTANCE(Database var1) {
Database.INSTANCE = var1;
}
public final void init(Context context) {
boolean initialized = INSTANCE != null; // error here
if (!initialized) { ...
It's clear that the issue is that the INSTANCE
variable must be referenced as Database.INSTANCE
.
Cannot understand, why the code compiles but throws run-time exception and how can I check if lateinit
variable is initialized?