Kotlin allows for the definition of singleton objects. In dependency injection (DI) frameworks like Spring or CDI, the life cycle of beans can be defined as singleton. Therefore, it seems sensible to declare Kotlin objects as beans for use in a DI container.
Is it indeed possible to declare a Kotlin object, e.g., as e Spring @Component
? If not, why not?
CodePudding user response:
Well it seems to work fine (and I don't see why it wouldn't work).
That being said, I don't think the definition of where a "singleton" is in fact 'single' is the same for kotlin and Spring. object seems to define singleton on a 1-per-ClassLoader basis, where 'singleton' of spring does it on a 1-per-ApplicationContext basis.
Most applications probably only use 1 of each, so there it would seem identical but if your application uses two or more of either ClassLoader or ApplicationContext it seems like it would end up being a confusing mess.
Imo the question would be: 'what do you hope to gain by using an object instead of a class?' I can't really see any advantages (but I might be wrong), so diverting from the convention that everyone uses seems like a bad idea.