Scala Tutorial

Basics

Control Statements

OOP Concepts

Parameterized - Type

Exceptions

Scala Annotation

Methods

String

Scala Packages

Scala Trait

Collections

Scala Options

Miscellaneous Topics

Singleton and Companion Objects in Scala

In Scala, both singleton objects and companion objects are special kinds of objects, but they serve different purposes. Let's dive into each one:

1. Singleton Objects:

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.

2. Companion Objects:

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:

  • Factory methods (to instantiate the associated class in various ways).
  • Implicit conversions or definitions.
  • Anything else that in Java or C# would be written as a static member of the class.

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!

Key Points:

  • Every class can have one companion object.
  • Companion objects and the classes they accompany must be defined in the same source file.
  • The class and its companion object can access each other's private members.

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.

  1. Scala Singleton Object Example:

    Define a simple singleton object.

    object MySingleton {
      def sayHello(): Unit = println("Hello, I'm a singleton object!")
    }
    
    // Usage
    MySingleton.sayHello()
    
  2. How to Create a Singleton Object in Scala:

    Declare a singleton object using the object keyword.

    object MySingleton {
      // methods and properties
    }
    
  3. 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
    }
    
  4. 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")
    }