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.
Advertisements