
- Scala - Home
- Scala - Overview
- Scala - Features
- Scala - Environment Setup
- Scala - Build Tool (SBT)
- Scala - REPL
- Scala - Dot & Dotty
- Scala - Basic Syntax
- Scala - Hello World Program
- Scala - Identifiers
- Scala - Keywords
- Scala - Comments
- Scala - Code Blocks
- Scala - Semicolon
- Scala - Constructs
- Scala - Expressions
- Scala - Input and Output
- Scala - Optional Braces
- Scala - Underscore (_)
- Data Types and Variables
- Scala - Data Types
- Scala - Type Bounds
- Scala - Context Bound
- Scala - Variances
- Scala - Type Hierarchy
- Scala - Variables
- Scala - Variable Scopes
- Scala - Literals
- Scala - Numeric Types
- Scala - Boolean Types
- Scala - Char Type
- Scala - Unit Types
- Scala - Strings
- Scala - Arrays
- Scala - Null Type
- Scala - Nothing
- Scala - Any Type
- Scala - AnyRef Type
- Scala - Unified Types
- Scala - Dates and Times
- Scala - Ranges
- Scala - Multidimensional Arrays
- Scala - WrappedArray
- Scala - StringBuilder
- Scala - String Interpolation
- Scala - StringContext
- Scala - Type Casting
- Scala var vs val
- Scala Operators
- Scala - Operators
- Scala - Rules for Operators
- Scala - Arithmetic Operators
- Scala - Relational Operators
- Scala - Logical Operators
- Scala - Bitwise Operators
- Scala - Assignment Operators
- Scala - Operators Precedence
- Scala - Symbolic Operators
- Scala - Range Operator
- Scala - String Concatenation Operator
- Scala Conditional Statements
- Scala - IF ELSE
- Scala - IF-ELSE-IF-ELSE Statement
- Scala - Nested IF-ELSE Statement
- Scala Loop Statements
- Scala - Loop Statements
- Scala - while Loop
- Scala - do-while Loop
- Scala - Nested Loops
- Scala - for Loop
- Scala - break Statement
- Scala - yield Keyword
- Scala Classes & Objects
- Scala - Classes & Objects
- Scala - Constructors
- Scala - Auxiliary Constructor
- Scala - Primary Constructor
- Scala - This Keyword
- Scala - Nested Classes
- Scala - Getters and Setters
- Scala - Object Private Fields
- Scala - Singleton Object
- Scala - Companion Objects
- Scala - Creating Executable Programs
- Scala - Stateful Object
- Scala - Enumerations
- Scala - Polymorphism
- Scala - Access Modifiers
- Scala - Apply Method
- Scala - Update Methods
- Scala - UnapplySeq Method
- Scala - Inheritance
- Scala - Extending a Class
- Scala - Method Overloading
- Scala - Method Overriding
- Scala - Generic Classes
- Scala - Generic Functions
- Scala - Superclass Construction
- Scala Methods & Functions
- Scala - Functions
- Scala - Main Methods
- Scala - Functions Call-by-Name
- Scala - Functions with Named Arguments
- Scala - Function with Variable Arguments
- Scala - Recursion Functions
- Scala - Default Parameter Values
- Scala - Functions without Parameters
- Scala - Implicit Parameters
- Scala - Higher-Order Functions
- Scala - Nested Functions
- Scala - Extension Methods
- Scala - Anonymous Functions
- Partially Applied Functions
- Scala - Lazy Val
- Scala - Pure Function
- Scala - Currying Functions
- Scala - Control Abstractions
- Scala - Corecursion
- Scala - Unfold
- Scala - Tail Recursion
- Scala - Infinite Sequences
- Scala - Dynamic Invocation
- Scala - Lambda Expressions
- Scala Collections
- Scala - Collections
- Mutable and Immutable Collections
- Scala - Lists
- Scala - Sets
- Scala - Maps
- Scala - TreeMap
- Scala - SortedMap
- Scala - Tuples
- Scala - Iterators
- Scala - Options
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Type Patterns
- Scala - Exception Handling
- Scala - Extractors
- Scala - Regular Expressions
- Scala Files I/O
- Scala - Files I/O
- Scala Advanced Concepts
- Scala - Closures
- Scala - Futures
- Scala - Promises
- Scala - Traits
- Scala - Trait Mixins
- Scala - Layered Traits
- Scala - Trait Linearization
- Scala - Sealed Traits
- Scala - Transparent Traits
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala - BDD Testing
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.