Search code examples
kotlinmicronaut

Why use @singleton instead using simply object


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?


Solution

  • 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()
    }
    
    1. It can't be just an object because takes a parameter.

    2. 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.