what is the best way to force the initialization o...
# getting-started
d
what is the best way to force the initialization of the fields on an object, ex
Copy code
object Config {
    val port = System.getenv("PORT") ?: 8080
}
i want to init this on startup
b
They're initialised together with the object. However kotlin's objects are lazy
Meaning they're only initialised upon the first request
So to force that on startup just call it in main ``` fun main() { Config }
d
is this considered the proper way of doing it ?
it’s what i’m currently doing, but it looks so wrong
b
Well not quite. It's the equvivalent of Config(), just makes it globally accessible afterwards
You could implement an object manager class/function, which would force the declared object initialisation:
Copy code
class ObjectManager {
  init {
    Object1
    Config
    AnotherObject
  }
}

fun main() {
  ObjectManager()
}
d
If you need something initialized at a specific time, then lazy singleton (which Kotlin's
object
is) is not the right pattern for you
d
hmm.. the alternative seems to be to make it a class, then create a top level lateinit Config and
Config = Config()
on startup 🤔
or provide the object with a
init()
method
b
Sounds like the initial idea with extra steps anyways
d
it feels like i’m missing something obvious
yeah
b
I'd say use dependency injection instead
👆 2
And make Config a class that's injected where needed
Have a look at Kodein
Quite simple to grasp and is kotlin-oriented. Also has a neat integration with ktor if you;re using it
d
thanks, will have a look
b
You can have a look at my sample project for example setup: https://gitlab.com/kotlin-examples/transaction-api
Uses ktor, kodein and spek for tests
c
Objects shouldn’t really be used for holding global state like this, because they can’t reliably track with the application lifecycle (by nature of being global). By wanting to have the
object
initialized at a specific time, you’re tying it to the application lifecycle. Dependency Injection is definitely the way to go here, for managing lifecycle-aware “global” objects.
j
I'm sorry for being thick, but is what you're saying that the config object will live throughout the application lifecycle, and it shouldn't (because that's wasteful use of memory)?
You can have the Kodein object being statically available (in Android, for example, it is common to use a property of the Application object)
https://kodein.org/Kodein-DI/?6.3/getting-started Wouldn't this also have the same memory footprint?
But I agree it makes sense if you're already using dependency injection