Reputation: 6566
I came across a piece of code in Scala that looks like this:
@Singleton
class MyClass {
// ...
}
But I thought objects were Singletons and classes were not. So is this basically equivalent to this?
object MyClass {
// ....
}
EDIT: Here is what I'm looking at.
Upvotes: 5
Views: 825
Reputation: 298818
@Singleton
usually refers to a managed singleton in an IOC (Inversion of Control) framework, like Guice (see Scopes) or Spring.
That's a difference to object
, which is a singleton managed by the ClassLoader.
In theory, you can have multiple applications running at the same time, using different @Singleton
objects of the same class. But they will all use the same object
as long as they share a ClassLoader.
Upvotes: 9
Reputation: 55569
No. By itself, the @Singleton
annotation does absolutely nothing. It is meant to be used by a dependency injection (DI) framework. @Singleton
signals to the DI framework that it should only instantiate one instance of that class if another class (or many) calls for it as a dependency.
There is nothing stopping you, however, from simply instantiating more instances of class MyClass
manually.
With object MyClass
, you have a singleton created and enforced by the Scala compiler.
Upvotes: 7