
- 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 - Methods
- Scala - Functions
- Scala - Methods vs 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 - Polymorphic Functions
- 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 - NumericRange
- Scala - Infinite Streams
- Scala - Parallel Collections
- Scala Advanced Types
- Scala - Union Types
- Scala - Intersection Types
- Scala - Type Aliases
- Scala - Structural Types
- Scala - Match Expression
- Scala - Singleton Type Operator
- Scala - Abstract Types
- Scala - Dependent Types
- Scala - Abstract Type Bounds
- Scala - Higher-Kinded Types
- Scala - Opaque Type Alias
- Scala - Path-Dependent Types
- Scala - Type Lambdas
- Scala - Type Inference
- Scala - Algebraic Data Types
- Scala Pattern Matching
- Scala - Pattern Matching
- Scala - Guards
- Scala - Variables in Patterns
- Scala - Type Patterns
- Scala - The Matchable Trait
- Scala - Matching Arrays
- Scala - Matching Lists
- Scala - Matching Tuples
- Scala - Exception Handling
- Scala - Extractors
- Scala - Pattern Bindings
- Scala - Regular Expressions
- Scala - Case Classes
- Scala - Partial Functions
- Scala - Packaging and Imports
- Scala - Implicit Imports
- Scala - Export Clauses
- Scala - Nested Packages
- Scala - Chained Packages
- Scala - Package Objects
- Scala Files I/O
- Scala - Files I/O
- Scala - Writing Files
- Scala - Listing Files
- Scala - Deleting Directories
- Scala - Check File Exists
- 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 - Process Management
- Scala - Scaladoc
- Scala - Literal Type Arithmetic
- Scala - Inline keyword
- Scala - Def, Var & Val
- Scala - Dropped Features
- Scala Unit Testing
- Scala - Unit Testing
- Scala - uTest
- Scala - MUnit
- Scala - ScalaTest Runner
- Scala - ScalaMock
- Scala - JUnit
- Scala - Mocking
- Scala - BDD Testing
Scala - Methods
This chapter takes you through the concept of methods in Scala programming. Methods are building blocks in Scala. You can define reusable blocks of code that perform specific tasks. You can call these methods whenever needed.
Introduction to Methods
Method is a function defined within a class, trait and object. Methods can take parameters. Method can perform actions and return values. So, you can organize code into logical units. So code can be modular and maintainable.
Method can be defined using the def keyword. Then it is followed by the method name, parameter list, return type, and method body.
Syntax
The syntax of the method in Scala -
def methodName(param1: Type1, param2: Type2): ReturnType = { // Method body // return some value of ReturnType }
Example
The following example defines and uses a simple method in Scala programming -
object Demo { def add(a: Int, b: Int): Int = { a + b } def main(args: Array[String]): Unit = { val sum = add(5, 3) println(s"The sum is: $sum") } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
The sum is: 8
In the example, there is an add method that takes two parameters of type Int. This method returns their sum. The Demo object calls this add method and prints the result.
Method Parameters
Methods can take zero or more parameters. These parameters are specified in the parameter list. Parameters are used to pass values into the method.
Syntax
The syntax of method parameters -
def methodName(param1: Type1, param2: Type2): ReturnType = { // Method body }
Example
The following example shows a method with multiple parameters in Scala programming -
object Demo { def multiply(a: Int, b: Int): Int = { a * b } def main(args: Array[String]): Unit = { val product = multiply(4, 5) println(s"The product is: $product") } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
The product is: 20
In the example, the multiply method takes two parameters of type Int. This method returns their product. The Demo object calls the multiply method and prints the result.
Default Parameters
You can also define default values for method parameters. If a parameter is not provided when the method is called. The default value is used.
Syntax
The syntax of default parameters in method -
def methodName(param1: Type1 = defaultValue1, param2: Type2 = defaultValue2): ReturnType = { // Method body }
Example
The following example shows a method with default parameters in Scala programming -
object Demo { def greet(name: String = "Guest"): Unit = { println(s"Hello, $name!") } def main(args: Array[String]): Unit = { greet("Alice") greet() } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Hello, Alice! Hello, Guest!
In the example, the greet method has a default parameter value of "Guest". It is used when there is no value of this parameter given by the user. Demo object calls the greet method with and without providing an argument.
Named Parameters
You can use parameter names when calling a method. So, the code is more readable and you can pass parameters in any order.
Syntax
The syntax of named parameters in method calling -
methodName(param1 = value1, param2 = value2)
Example
The following example shows the use of named parameters in Scala -
class Rectangle { def area(length: Double, width: Double): Double = { length * width } } object Demo { def main(args: Array[String]): Unit = { val rect = new Rectangle() val area1 = rect.area(length = 5.0, width = 3.0) val area2 = rect.area(width = 3.0, length = 5.0) println(s"Area1: $area1") // Area1: 15.0 println(s"Area2: $area2") // Area2: 15.0 } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Area1: 15.0 Area2: 15.0
In the example, the Rectangle class defines area method. This method takes two parameters: length and width. Demo object calls the area method with named parameters. So you set arguments in any order. Hence order does not matter here.
Method Overloading
You can define multiple methods with the same name but different parameter lists. The appropriate method is selected based on the arguments provided. This is known as method overloading.
Syntax
The syntax of method overloading -
def methodName(param1: Type1): ReturnType = { // Method body } def methodName(param1: Type1, param2: Type2): ReturnType = { // Method body }
Example
The following example shows method overloading in Scala programming -
class Calculator { def add(x: Int, y: Int): Int = { x + y } def add(x: Int, y: Int, z: Int): Int = { x + y + z } } object Demo { def main(args: Array[String]): Unit = { val calc = new Calculator() val result1 = calc.add(5, 3) val result2 = calc.add(1, 2, 3) println(s"Sum (2 args): $result1") // Sum (2 args): 8 println(s"Sum (3 args): $result2") // Sum (3 args): 6 } }
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 (2 args): 8 Sum (3 args): 6
In the example, the Calculator class defines two add methods with the same name but different number of parameters. One that takes two parameters and another that takes three parameters. Demo object calls each version of the add method based on the number of arguments.
Varargs (Variable Arguments)
You can define methods that accept a variable number of arguments. You need to use * symbol after the parameter type for variable length parameters. This is used when you do not know the exact number of arguments to be passed.
Syntax
The syntax of variable number of parameters using * symbol in Scala -
def methodName(params: Type*): ReturnType = { // Method body }
Example
The following example shows a method with variable length parameters in Scala programming -
class Summation { def sum(nums: Int*): Int = { nums.sum } } object Demo { def main(args: Array[String]): Unit = { val summation = new Summation() println(summation.sum(1, 2, 3)) // 6 println(summation.sum(4, 5, 6, 7)) // 22 } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
6 22
In the example, the Summation class defines the sum method. This method takes a variable number of integer arguments using the Int* syntax. So, you can pass any number of arguments during method calls. The Demo object calls the sum method with different numbers of arguments.
Higher-Order Methods
Methods can take other methods and functions as parameters. Methods can also return methods and functions as results. These methods are known as higher order methods. So, there can be abstractions and code reuse.
Syntax
The syntax of higher order method is -
def methodName(f: (DataType1, DataType2) => ReturnType): ReturnType = { // method body }
Example
The following example shows using higher-order methods in Scala programming -
class MathOperations { def applyOperation(x: Int, y: Int, op: (Int, Int) => Int): Int = { op(x, y) } } object Demo { def main(args: Array[String]): Unit = { val mathOps = new MathOperations() val add = (a: Int, b: Int) => a + b val multiply = (a: Int, b: Int) => a * b println(mathOps.applyOperation(5, 3, add)) // 8 println(mathOps.applyOperation(5, 3, multiply)) // 15 } }
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
8 15
In the example, the MathOperations class defines applyOperation method. It takes two integers and a function (operation) as parameters. Demo object passes different functions (addition and multiplication) to the applyOperation method.
Methods Summary
- Methods in Scala are reusable blocks of code. Methods perform various tasks and can take parameters and return values.
- Methods can have default parameters, named parameters, and variable length parameters.
- You can define multiple methods with the same name but different parameter lists. This is known as method overloading.
- Methods can have default parameters, named parameters, and can take a variable number of arguments.
- Methods can also take methods and functions as arguments. Methods can also return method and function.