CodeToLive

Scala Functions & Methods

Master function definitions, higher-order functions, and methods in Scala.

Function Definitions

Scala has first-class functions. Here's how to define them:

// Simple function
val add = (x: Int, y: Int) => x + y

// Function with explicit return type
val multiply: (Int, Int) => Int = (x, y) => x * y

// Calling functions
println(add(2, 3))      // 5
println(multiply(2, 3)) // 6

Methods

Methods are defined with the def keyword and belong to classes/traits/objects:

object MathUtils {
  // Method definition
  def square(x: Int): Int = x * x
  
  // Multi-line method
  def factorial(n: Int): Int = {
    if (n <= 1) 1
    else n * factorial(n - 1)
  }
}

// Calling methods
println(MathUtils.square(5))      // 25
println(MathUtils.factorial(5))   // 120

Higher-Order Functions

Functions that take other functions as parameters or return functions:

// Function that takes another function as parameter
def operateOnNumbers(a: Int, b: Int, operation: (Int, Int) => Int): Int = {
  operation(a, b)
}

val sum = operateOnNumbers(5, 3, (x, y) => x + y)
val product = operateOnNumbers(5, 3, _ * _)  // Using placeholder syntax

// Function that returns another function
def multiplier(factor: Int): Int => Int = {
  (x: Int) => x * factor
}

val timesTwo = multiplier(2)
println(timesTwo(5))  // 10

Anonymous Functions

Functions without a name (lambda expressions):

val numbers = List(1, 2, 3, 4, 5)

// Using anonymous function
val doubled = numbers.map(x => x * 2)

// Even more concise with placeholder syntax
val squared = numbers.map(_ * _)

Currying

Transforming a function with multiple arguments into a sequence of functions with single arguments:

// Normal function
def add(x: Int, y: Int): Int = x + y

// Curried version
def addCurried(x: Int)(y: Int): Int = x + y

// Usage
val addTwo = addCurried(2)_  // Partially applied
println(addTwo(3))           // 5
← Back to Tutorials