0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Functions as Values

First-class functions.

Functions are values

In Scala, functions are first-class values. You can store them in variables, pass them as arguments, and return them from other functions, just like numbers or strings.

object Main {
  def main(args: Array[String]): Unit = {
    val increment: Int => Int = x => x + 1
    println(increment(5))
  }
}

Function type syntax

The type Int => String means a function taking an Int and returning a String. Multiple parameters use parentheses: (Int, Int) => Int.

object Main {
  def main(args: Array[String]): Unit = {
    val add: (Int, Int) => Int = (a, b) => a + b
    val label: Int => String = n => s"value=$n"
    println(add(3, 4))
    println(label(7))
  }
}

All lessons in this course

  1. Functions as Values
  2. Currying
  3. Composition
  4. Closures
← Back to Scala for Backend Engineering & Functional Programming