user3685285
user3685285

Reputation: 6566

is @Singleton on a class the same as an object in Scala?

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

Answers (2)

Sean Patrick Floyd
Sean Patrick Floyd

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

Michael Zajac
Michael Zajac

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

Related Questions