Google News
logo
Scala - Interview Questions
What is the purpose of the 'apply' method in Scala?
In Scala, the `apply` method is a special method that can be defined in a class or object. It is used to create an instance of the class or object using a concise syntax that resembles function invocation. The `apply` method allows instances to be created without explicitly calling the constructor using the `new` keyword.

Here are the main purposes and characteristics of the `apply` method :

1. Object Creation : By defining an `apply` method in a class or object, you can use that class or object as if it were a function, creating new instances by invoking it with arguments.

2. Concise Syntax : The `apply` method provides a more compact and natural way to create instances by using parentheses and passing arguments, similar to calling a function.

3. Implicit Invocation : When the `new` keyword is omitted, the Scala compiler automatically invokes the `apply` method when the class or object is used as a function call.

4. Overloading : Multiple `apply` methods can be defined with different parameter lists in the same class or object, allowing for method overloading based on argument types.

5. Uniform Access Principle : By providing an `apply` method, you can make the creation of instances consistent with other operations performed on objects, such as method calls or property access.

Here's an example to illustrate the usage of the `apply` method :
class MyClass(val name: String, val age: Int)

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

val myObj = MyClass("John", 30)
println(myObj.name) // Output: John
println(myObj.age) // Output: 30​

In this example, the `MyClass` object defines an `apply` method that takes a name and age as arguments. Inside the `apply` method, a new instance of `MyClass` is created using the provided arguments.

By omitting the `new` keyword, the `MyClass` object can be used as if it were a function. The `apply` method is implicitly invoked with the provided arguments, and a new instance of `MyClass` is created. This creates a more concise and intuitive syntax for object creation.

The `apply` method can be overloaded with different parameter lists, allowing for different ways to create instances of the class or object based on the arguments provided.

Overall, the `apply` method provides a convenient and expressive way to create instances of a class or object in Scala, enabling a more functional and concise coding style.
Advertisement