Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 579
user3685285 Avatar asked Mar 16 '17 16:03

user3685285


People also ask

What is difference between object and class in Scala?

Difference Between Scala Classes and Objects Definition: A class is defined with the class keyword while an object is defined using the object keyword. Also, whereas a class can take parameters, an object can't take any parameter. Instantiation: To instantiate a regular class, we use the new keyword.

What is an object in Scala?

In Scala, an object is a named instance with members such as fields and methods. An object and a class that have the same name and which are defined in the same source file are known as companions. Companions has special access control properties, which is covered under Scala/Access modifiers.

Is Scala object a singleton?

Instead of static keyword Scala has singleton object. A Singleton object is an object which defines a single object of a class. A singleton object provides an entry point to your program execution. If you do not create a singleton object in your program, then your code compile successfully but does not give output.

What is the difference between singleton object and companion object?

In scala, when you have a class with same name as singleton object, it is called companion class and the singleton object is called companion object. The companion class and its companion object both must be defined in the same source file.


1 Answers

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

like image 102
Sean Patrick Floyd Avatar answered Sep 26 '22 13:09

Sean Patrick Floyd