5

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.

user3685285
  • 6,066
  • 13
  • 54
  • 95

2 Answers2

9

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

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
7

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.

Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
  • Does that mean `@Singleton` on an `object` is redundant? Or more specifically, `object` implies `@Singleton`, but `@Singleton` does not imply `object`? – user3685285 Mar 21 '17 at 15:33
  • 1
    @user3685285 Kind of. It just wouldn't do anything. `@Singleton` on an `object` would be ignore by a DI framework, because DI frameworks are only concerned with constructing classes. – Michael Zajac Mar 21 '17 at 16:02