Reputation: 77
I know that singleton is a ''class that has only one instance and provides a global point of access to it".But what does Singleton in scala means ?How does Singleton object applies concept of singleton in scala ?What does Singleton Object / Object creates in scala?
Upvotes: 1
Views: 122
Reputation: 143
An object is a class that has only one instance of that class. This is created whenever the object is referenced otherwise it is not created. It exactly behaves as an Lazy Evaluation.
Here’s an example of an object with a method:
package logging
object Logger {
def info(message: String): Unit = println(s"INFO: $message")
}
This info method can be used anywhere from the program.
Let's see how to use the info method in the program.
`import logging.Logger.info
class Project(name: String, daysToComplete: Int)
class Test {
val project1 = new Project("TPS Reports", 1)
val project2 = new Project("Website redesign", 5)
info("Created projects") // Prints "INFO: Created projects"
}`
Upvotes: 0
Reputation: 108101
An object is a class that has exactly one instance. It is created lazily when it is referenced, like a lazy val.
https://docs.scala-lang.org/tour/singleton-objects.html
So whenever you do
object SomeObject
the compiler will create a class and a single instance of that class, that it's lazily initialized.
This makes object
a singleton in the Java sense of the term (guaranteed single instance of a class)
Upvotes: 2