Skip to content
AgileLogics
5 min read

Methods

Prerequisites: Blocks and expressions

A method is a named, reusable block of code, defined with def:

def square(n: Int): Int = n * n

def greet(name: String): String =
  val cleaned = name.trim.capitalize
  s"Hello, $cleaned!"

def printBanner(title: String): Unit =
  println("=" * 20)
  println(title)
  println("=" * 20)

@main def methods(): Unit =
  println(square(7))
  println(greet("  ada "))
  printBanner("Report")
49
Hello, Ada!
====================
Report
====================
  • Parameters need types: (n: Int).
  • The return type comes after the parameters: : Int.
  • The body's last expression is the result — no return needed.
  • A one-line body can go on the same line as =.
  • Methods that only do something (like printing) return Unit.

Methods can be defined at the top level of a file (outside any class), as here.

Several parameters and results

def minMax(numbers: List[Int]): (Int, Int) =
  (numbers.min, numbers.max)

@main def tuples(): Unit =
  val (low, high) = minMax(List(4, 9, 1, 7))
  println(s"low=$low high=$high")
low=1 high=9

Return several values as a tuple and unpack it with val (a, b) = ... (the Tuples lesson covers them).

Recursion

A method can call itself. Recursive methods must declare their return type:

def factorial(n: Int): BigInt =
  if n <= 1 then 1 else n * factorial(n - 1)

@main def recursion(): Unit =
  println(factorial(5))
  println(factorial(25))
120
15511210043330985984000000

Practice

Write isEven(n: Int): Boolean and use it to print the even numbers from 1 to 10.

Show solution
def isEven(n: Int): Boolean = n % 2 == 0

@main def evens(): Unit =
  for n <- 1 to 10 if isEven(n) do println(n)
2
4
6
8
10