Function values
A method is not a value: it belongs to a class, an object or a file, and it is called by its name. A function value is a value like any other — it can sit in a val, travel as an argument and come back as a result. The two are close enough that Scala turns one into the other where a function is expected, and this lesson is about the value.
A function in a val
A lambda is written with an arrow: the parameters on the left, the body on the right. The type of each parameter is declared where the compiler cannot infer it, and the result type follows the body. A function value is called with parentheses like a method, and apply is the method that call stands for:
functions.scala
@main def functions(): Unit =
val double = (n: Int) => n * 2
val add = (a: Int, b: Int) => a + b
println(double(21))
println(double.apply(21))
println(add(2, 3))
val increment: Int => Int = _ + 1
println(increment(41))
scala-cli run --server=false functions.scala
42
42
5
42
double.apply(21) is the call behind double(21), and the underscore of increment is a parameter the compiler names for you: _ + 1 with the type Int => Int on the left is (n: Int) => n + 1. The underscore is only a placeholder; a function that uses its argument twice writes the parameter out.
The type of a function
Int => String is the type of a function of one argument, and it is the same type as Function1[Int, String]. The number in the name is the count of parameters: (String, Int) => String is Function2[String, Int, String], and the arrow form of a function that returns a function, Int => Int => Int, groups to the right.
The type is what a parameter accepts. A method declared with an arrow type takes any function of that shape — a lambda, a method converted to a function, or another function value — and does not care which one it gets:
A method as a value
A method is converted to a function where a function is expected, so the name of a method can be passed without parentheses or an arrow. The compiler checks the shape: a method of the wrong arity does not convert.
method.scala
def square(n: Int): Int = n * n
@main def methodAsValue(): Unit =
val f: Int => Int = square
println(f(5))
println(List(1, 2, 3).map(square))
println(List(1, 2, 3).map(f))
val format: (String, Int) => String = (name, n) => s"$name: $n"
println(format("total", 42))
scala-cli run --server=false method.scala
25
List(1, 4, 9)
List(1, 4, 9)
total: 42
val f: Int => Int = square is the conversion written out, and map(square) is the same conversion in an argument position. A method that is converted this way is a function of its own: the value f keeps the behaviour without the name, which is what makes it passable.
Related
- Higher-order functions: a method that takes one of these values.
- Closures: a function that keeps a value from where it was written.
- Methods and parameters: the method side of the pair.
- map, flatMap, filter and fold: the methods that take a function.
Article author: Arthur Isaev