Google News
logo
Scala - Interview Questions
What is the role of the 'object' keyword in Scala?
In Scala, the `object` keyword has multiple roles and serves various purposes:

1. Singleton Objects : When the `object` keyword is used to define a named object, it creates a singleton instance of a class. A singleton object is a class that has only one instance, and its definition and initialization occur simultaneously. Singleton objects are commonly used to hold utility methods, define entry points to applications, or provide global state or resources.
   object MySingleton {
     def doSomething(): Unit = {
       println("Doing something...")
     }
   }

   MySingleton.doSomething()​

   In this example, `MySingleton` is a singleton object that defines a method `doSomething()`. The object can be accessed directly, and its methods can be invoked without the need for instantiation. This allows for a convenient and concise way to organize utility methods or access shared resources.

2. Companion Objects : In Scala, a companion object is an object that has the same name as a class and is defined in the same source file. The companion object and class are tightly linked, and they can access each other's private members. Companion objects are often used to define factory methods or provide static-like behavior to classes.
   class MyClass(name: String)

   object MyClass {
     def apply(name: String): MyClass = new MyClass(name)
   }

   val myObject = MyClass("Example")​
   In this example, the `MyClass` class is defined, and its companion object provides a factory method `apply` to create instances of `MyClass`. By convention, the `apply` method is a special method that can be called directly on the companion object, as shown in `MyClass("Example")`. This syntax creates a new instance of `MyClass` using the factory method defined in the companion object.

3. Entry Points : The `object` keyword can also be used to define entry points to Scala applications. When an object extends the `App` trait, it provides a convenient way to define the entry point of the application without explicitly writing a `main` method.
   object MyApp extends App {
     println("Hello, Scala!")
   }​

   In this example, `MyApp` extends the `App` trait, which comes with predefined behavior to execute the code inside the object. The code within the object's body is executed when the application is run. In this case, it simply prints "Hello, Scala!" to the console.

The `object` keyword in Scala allows you to define singleton objects, companion objects, and entry points to applications. It provides a way to organize code, create singleton instances, define static-like behavior, and define entry points in a concise and convenient manner.
Advertisement