Eager initialize object in kotlin?

Viewed 1826

I'm trying to declare my android sqlite migrations in object declarations. Each extends the interface Migration, and I want to have each one register themselves upon initialization with the Migrator object, which being an object, is also a singleton. Unfortunately (I'm realizing this late) kotlin objects are lazily initialized, so my migrations have to be used somewhere to register themselves.

I can accept having to use reflections or annotations, but have no bearing for if that's a good idea or how to follow convention going that direction.

3 Answers

Simply writing the object name into your main function (or whereever you want to force the initialization) works:

//Main.kt
fun main() {
    EagerObject
    //...
}

//EagerObject.kt
object EagerObject {
    //...
}

I really don't see why you couldn't add an init block to your Migrator class, that way you can always see what migrations are being registered and ensure they are registered when the migrator gets referenced.

Something like this could work (or just a list.add call, depends on how you would register them).

object Migrator {
    init {
        listOf(UpdateNames, TableRename).forEach(Migration::register)

        // Or, as I said, something like this would make more sense
        migrations = buildList {
            add(UpdateNames)
            add(TableRename)
        }
    }

    [...]
}

I hope this makes my idea clear, I wrote this on my phone at 2am so this might as well not compile. Sorry in advance :)

Related