In Kotlin, a common use for object is using it for singletons, like:
object MyObject {
...
}
However, when using micronaut framework, the official documentation recommends using something like this:
@Singleton
class V8Engine : Engine {
override var cylinders = 8
override fun start(): String {
return "Starting V8"
}
}
Why can't I use simply object instead of using annotation @Singleton with a class?
With a @Singleton
, Micronaut can automatically manage dependencies between beans. If you go with the other class in https://docs.micronaut.io/latest/guide/ioc.html#beans, translated to Kotlin:
@Singleton
class Vehicle(private val engine: Engine) {
public fun start() = engine.start()
}
It can't be just an object
because takes a parameter.
This parameter is discovered by Micronaut to be the singleton instance of V8Engine
, which needs that to be a @Singleton
and not an object
.
Of course, in this case you could just directly use V8Engine
in Vehicle
; but it's easier to change e.g. if you want Engine
not to be a singleton anymore.