Functions in Scala

Functions are central in Scala. We’ll learn about functions with a few different examples.

object Functions {
  // Here's a function that takes two Ints and returns
  // their sum as an Int.
  def plus(a: Int, b: Int): Int = {
    // Scala allows implicit returns, so the last expression
    // in a function is automatically returned.
    a + b
  }

  // In Scala, you can omit curly braces for single-expression functions
  def plusPlus(a: Int, b: Int, c: Int): Int = a + b + c

  def main(args: Array[String]): Unit = {
    // Call a function just as you'd expect, with
    // name(args).
    val res = plus(1, 2)
    println(s"1+2 = $res")

    val res2 = plusPlus(1, 2, 3)
    println(s"1+2+3 = $res2")
  }
}

To run the program:

$ scala Functions.scala
1+2 = 3
1+2+3 = 6

There are several other features to Scala functions. One is multiple return values, which we’ll look at next.

Key differences from the original code:

  1. Scala uses object instead of package for top-level definitions.
  2. Function definitions start with def in Scala.
  3. Scala uses : to separate parameter names from their types, and => to separate the parameter list from the function body for single-expression functions.
  4. Scala allows implicit returns, so the return keyword is often omitted.
  5. Scala’s println is used instead of fmt.Println.
  6. String interpolation is used in Scala with s"..." syntax.
  7. The main function in Scala takes an Array[String] as an argument and has a return type of Unit.

These changes reflect idiomatic Scala while maintaining the structure and purpose of the original example.