Scala Tutorial
Basics
Control Statements
OOP Concepts
Parameterized - Type
Exceptions
Scala Annotation
Methods
String
Scala Packages
Scala Trait
Collections
Scala Options
Miscellaneous Topics
In Scala, both singleton objects and companion objects are special kinds of objects, but they serve different purposes. Let's dive into each one:
A singleton object is an object that is the sole instance of its own type. This concept is similar to the Singleton design pattern in other languages, but in Scala, it's provided natively through the object
keyword.
Here's a basic example:
object Singleton { def greet(): Unit = { println("Hello from the Singleton object!") } } // Usage: Singleton.greet() // Outputs: Hello from the Singleton object!
In the above code, Singleton
is an instance of its own anonymous class. You can directly call methods on it, and you don't (and can't) create instances of it using new
.
When an object
shares the same name with a class
or trait
and is defined in the same source file, it's called a companion object. The class/trait and its companion object can access each other's private members. Companion objects are typically used for:
Here's an example using a class and its companion object:
class Companion(val name: String) { def greet(): Unit = { println(s"Hello, $name!") } } object Companion { // Factory method def apply(name: String): Companion = { new Companion(name) } def greetEveryone(): Unit = { println("Hello, everyone!") } } // Usage: val person = Companion("Alice") // This uses the apply method from the companion object person.greet() // Outputs: Hello, Alice! Companion.greetEveryone() // Outputs: Hello, everyone!
class
can have one companion object.In practice, singleton objects (those without a companion class) are used for utility functions and constants, among other things. Companion objects, on the other hand, usually contain methods and fields related to the accompanying class, like factory methods or implicit conversions.
Scala Singleton Object Example:
Define a simple singleton object.
object MySingleton { def sayHello(): Unit = println("Hello, I'm a singleton object!") } // Usage MySingleton.sayHello()
How to Create a Singleton Object in Scala:
Declare a singleton object using the object
keyword.
object MySingleton { // methods and properties }
Companion Object Pattern in Scala:
Combine a class and its companion object to implement the companion object pattern.
class MyClass { // class members } object MyClass { // companion object members }
Scala Companion Object Inheritance:
Companion objects can extend classes or traits.
trait Logger { def log(message: String): Unit } class MyClass object MyClass extends Logger { def log(message: String): Unit = println(s"Log: $message") }