Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eager initialize object in kotlin?

Tags:

android

kotlin

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.

like image 417
Catalyst Avatar asked May 21 '17 01:05

Catalyst


2 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 {
    //...
}
like image 92
dranjohn Avatar answered Oct 13 '22 01:10

dranjohn


As a workaround you can switch from object declarations to object expressions with global variables:

Eager:

val A = object {
    init { println("eager") }
}

Lazy:

object A {
    init { println("lazy") }
}
like image 33
voddan Avatar answered Oct 13 '22 03:10

voddan