Scala - Apply Method



This chapter takes you through the concept of the apply method in Scala programming. The apply method creates objects. It is used to implement custom behavior for classes and objects.

The apply() Method

The apply() method in Scala is a special method that is syntactically different from other methods. It can be defined in both classes and objects. So, instances of the class and the object itself are called, like functions.

The apply() method is used to define behavior that should be executed when instance of the class is called as a function.

Syntax

The syntax of apply method in Scala is -

class Demo {
   def apply(param: Type): ReturnType = {
      // method body
   }
}

Example

The following example shows a simple apply method in Scala programming -

class Adder {
   def apply(x: Int, y: Int): Int = x + y
}

object Demo {
   def main(args: Array[String]): Unit = {
      val adder = new Adder
      println(s"Sum of 3 and 5: ${adder(3, 5)}")
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Sum of 3 and 5: 8

In the example, Adder class has apply method that adds two integers. Demo object uses the apply method by calling an instance of Adder as if it were a function.

apply Method in Companion Objects

The apply method is also used in companion objects. It is used to create instances of a class without using the new keyword.

Syntax

The syntax of apply method in companion object in Scala is -

class Demo {
   // class definition
}

object Demo {
   def apply(param: Type): Demo = {
      new Demo(param)
   }
}

Example

The following example shows the apply method in a companion object.

class Person(val name: String, val age: Int)

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

object Demo {
   def main(args: Array[String]): Unit = {
      val person = Person("John", 25)
      println(s"Name: ${person.name}, Age: ${person.age}")
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Name: John, Age: 25

In the example, Person class has a companion object with an apply method. It creates new Person instance. Demo object creates Person instance without using the new keyword.

apply Method in Case Classes

Case classes in Scala automatically come with an apply method in their companion object. So, it is easy to create instances.

Syntax

The syntax of apply method in case classes is -

case class Demo(param: Type)

Example

The following example shows the apply method in a case class.

case class Point(x: Int, y: Int)

object Demo {
   def main(args: Array[String]): Unit = {
      val point = Point(5, 10)
      println(s"Point x: ${point.x}, y: ${point.y}")
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Point x: 5, y: 10

In the example, Point case class automatically provides an apply method. So instances can be created without the new keyword. Demo object shows this by creating a Point instance.

Custom apply Methods

Custom apply methods can be defined to perform more logic when creating instances.

Syntax

The syntax of custom apply method is -

class Demo(val param: Type)

object Demo {
   def apply(param: Type): Demo = {
      // custom logic
      new Demo(param)
   }
}

Example

The following example shows a custom apply method in Scala programming -

class Rectangle(val length: Int, val width: Int) {
   def area: Int = length * width
}

object Rectangle {
   def apply(length: Int, width: Int): Rectangle = {
      require(length > 0 && width > 0, "Length and width must be positive")
      new Rectangle(length, width)
   }
}

object Demo {
   def main(args: Array[String]): Unit = {
      val rect = Rectangle(5, 3)
      println(s"Area of the rectangle: ${rect.area}")
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Area of the rectangle: 15

In the example, Rectangle class has a companion object with a custom apply method. It includes validation logic. Demo object creates Rectangle instance and calculate its area.

Multiple apply Methods

Multiple apply methods can be defined in a companion object to provide different ways of creating instances.

Syntax

The syntax for applying multiple apply methods is -

class Demo(val param1: Type, val param2: Type)

object Demo {
   def apply(param1: Type): Demo = new Demo(param1, defaultParam2)
   def apply(param1: Type, param2: Type): Demo = new Demo(param1, param2)
}

Example

The following example shows multiple apply methods in Scala -

class Circle(val radius: Double) {
   def area: Double = Math.PI * radius * radius
}

object Circle {
   def apply(radius: Double): Circle = new Circle(radius)
   def apply(diameter: Double, isDiameter: Boolean): Circle = new Circle(diameter / 2)
}

object Demo {
   def main(args: Array[String]): Unit = {
      val circle1 = Circle(5)
      val circle2 = Circle(10, isDiameter = true)
    
      println(s"Area of circle1: ${circle1.area}")
      println(s"Area of circle2: ${circle2.area}")
   }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Area of circle1: 78.53981633974483
Area of circle2: 78.53981633974483

In the example, Circle class has a companion object with two apply methods. So, these provide different ways to create a Circle instance. Demo object uses these methods to create circles and calculates their areas.

The apply() Method Summary

  • The apply method in Scala creates objects. It is used to implement custom behavior for classes and objects.
  • The apply method can be defined in both classes and companion objects. So, instances are called, like functions.
  • Case classes automatically come with an apply method. So, it is easy to create instances without the new keyword.
  • Custom apply methods can include additional logic. For example, validation, when creating instances.
  • Multiple apply methods can be defined in a companion object to provide different ways of creating instances.
Advertisements