Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 37 ยท Language Basics

Methods and Functions

Learn Scala def methods, default and named arguments, varargs, function values and lambdas, higher-order functions, currying, by-name parameters and closures.

Functions are the main building blocks of Scala programs. You will define methods with def, pass functions as values, write short lambdas, and return functions from other functions. This lesson explains how methods and function values differ, then covers parameters (default, named, repeated, by-name), higher-order functions, currying and closures. The Scala is read-only; Java and Kotlin demos run live.

Defining a method with def

SCALA
def add(a: Int, b: Int): Int =
  a + b

def greet(name: String): String = s"Hello, $name"

def logLine(text: String): Unit =
  println(s"[log] $text")

A method has a name, typed parameters, a result type and a body. The result type is optional for non-recursive methods (the compiler infers it), but write it on public methods so the documentation is clear. A method with Unit result is called for its side effect.

A method without parameters can omit the parentheses:

SCALA
def pi = 3.14159
def now(): Long = System.currentTimeMillis()

By convention, empty parentheses signal a side effect (now()), no parentheses signal a plain computation (pi). Scala 3 enforces this when you call Java-style methods.

Default and named arguments

SCALA
def connect(host: String, port: Int = 5432, secure: Boolean = true): String =
  s"$host:$port secure=$secure"

connect("db.local")                      // db.local:5432 secure=true
connect("db.local", 3306)                // db.local:3306 secure=true
connect("db.local", secure = false)      // db.local:5432 secure=false
connect(port = 1, host = "x")            // x:1 secure=true

Named arguments make calls readable and let you skip defaults. Java has no default parameters. Kotlin does, as this demo shows:

Kotlin Default and named arguments (Kotlin comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Repeated parameters (varargs)

SCALA
def total(numbers: Int*): Int = numbers.sum

total()            // 0
total(1, 2, 3)     // 6
val xs = List(4, 5)
total(xs*)         // 9: pass a collection with `*`

Inside the method, numbers is a Seq[Int]. In Scala 2, the splat was written xs: _*.

Recursion

Methods can call themselves. A recursive method needs an explicit result type:

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

For deep recursion, write the call in tail position and annotate it. The compiler then turns it into a loop and fails to compile if it cannot:

SCALA
import scala.annotation.tailrec

def sumTo(n: Int): Long =
  @tailrec
  def loop(i: Int, acc: Long): Long =
    if i > n then acc else loop(i + 1, acc + i)
  loop(1, 0)

sumTo(100) is 5050. The nested loop is a local method: you can define methods inside methods to keep helpers private.

Function values and lambdas

A function value is an object you can store in a variable or pass around. Its type is written A => B.

SCALA
val double: Int => Int = x => x * 2
val add: (Int, Int) => Int = (a, b) => a + b

double(21)     // 42
add(2, 3)      // 5

Short forms with the placeholder _:

SCALA
val inc: Int => Int = _ + 1
List(1, 2, 3).map(_ * 10)     // List(10, 20, 30)
List("a", "b").map(_.toUpperCase) // List(A, B)

Each _ stands for the next parameter, so _ + _ is (a, b) => a + b. Use it for short one-liners; name the parameter when the body is longer.

Methods vs functions

A method belongs to a class or object and is not a value. A function is a value. Scala converts a method into a function automatically when needed (this is called eta-expansion):

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

List(1, 2, 3).map(square)      // List(1, 4, 9)
val f: Int => Int = square     // method turned into a function value

Higher-order functions

A function that takes or returns a function is higher-order. This is the basis of the collection methods you will use daily:

SCALA
def applyTwice(f: Int => Int, x: Int): Int = f(f(x))

applyTwice(_ + 3, 10)     // 16
applyTwice(_ * 2, 5)      // 20

Returning a function:

SCALA
def multiplier(factor: Int): Int => Int =
  n => n * factor

val triple = multiplier(3)
triple(7)    // 21

The same two functions in Java, runnable:

Java Higher-order functions in Java (comparison)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Closures

A function can use variables from the place where it was defined. It "closes over" them:

SCALA
var hits = 0
val onClick = () => hits += 1
onClick(); onClick()
println(hits)       // 2

The lambda captures the variable hits itself, not a copy.

Currying and multiple parameter lists

A method can have several parameter lists. Calling it with only the first returns a function that waits for the rest:

SCALA
def addTax(rate: Double)(price: Double): Double = price * (1 + rate)

val withVat = addTax(0.2)   // eta-expanded: Double => Double
withVat(100)                // 120.0
addTax(0.2)(50)             // 60.0

Multiple lists are also how Scala lets you pass a block as the last argument:

SCALA
def timed[A](label: String)(body: => A): A =
  val start = System.nanoTime()
  val result = body
  println(s"$label took ${(System.nanoTime() - start) / 1000} us")
  result

By-name parameters

body: => A is a by-name parameter: the argument is not evaluated at the call. It is evaluated each time the parameter is used. That lets you write your own control structures:

SCALA
def unless(cond: Boolean)(action: => Unit): Unit =
  if !cond then action

unless(1 > 2):
  println("runs, because 1 > 2 is false")

Compare with a normal (by-value) parameter, which is evaluated once, before the call.

Anonymous functions with pattern matching

SCALA
val pairs = List((1, "one"), (2, "two"))
pairs.map { case (n, word) => s"$n=$word" }
// List(1=one, 2=two)

Common mistakes

  • Omitting = before the body, which declares a method with no implementation.
  • Forgetting the result type on a recursive method.
  • Using _ twice in nested lambdas and getting a surprising meaning.
  • Using return in lambdas; it can throw an exception in Scala. Let the last expression be the value.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of the function x => x * 2 over Int?

    A function from Int to Int has the type Int => Int.
  2. 2. What does the _ in List(1, 2, 3).map(_ * 10) stand for?

    The underscore placeholder stands for the parameter, so _ * 10 is x => x * 10.
  3. 3. What is special about a by-name parameter written body: => A?

    By-name arguments are evaluated at each use inside the method, which allows custom control structures.
  4. 4. What does @tailrec do?

    The annotation makes the compiler fail if the method is not tail-recursive, guaranteeing no stack growth.
  5. 5. How do you pass an existing list xs to a varargs parameter in Scala 3?

    Append * to the argument to splat a collection into a repeated parameter.

Summary

  • def name(params): Result = body defines a method; the last expression is the result.
  • Parameters can have defaults, be named at the call, or be repeated (Int*).
  • Function values have types like Int => Int; _ and lambdas keep them short.
  • Higher-order functions, closures, currying and by-name parameters are core tools.
  • Use @tailrec to guarantee that a recursive method does not overflow the stack.

Next: Arrays, Seq and Buffers