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.
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.
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.
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.
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.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With