Function values
In Scala a function is a value like other values. It can be
- assigned to another variable,
- passed as a function parameter
- returned as function value
Function as variable
The function value is the function name.
Calling the function is adding the parameter list between round brackets
This way we can convert a method into a function
def add(a: Int, b: Int): Int = a + b
val adder = add
val result = adder(3, 4)
In the example usage, we define a sequence of input numbers and pass it to transformNumbers, along with a function that squares its input. The result is a new sequence with the squares of the input values.
Function as parameter
In Scala, you can pass functions as parameters to other functions. This allows you to define higher-order functions, which are functions that take other functions as arguments or return functions as values.
Here's an example of defining a function that takes another function as a parameter:
def transformNumbers(numbers: List[Int], f: Int => Int): List[Int] =
numbers.map(f)
// Example usage
val input = List(1, 2, 3, 4, 5)
val output = transformNumbers(input, x => x * x) // List(1, 4, 9, 16, 25)
In this example, we define a function named transformNumbers that takes two parameters: a sequence of Int values named numbers, and a function named f that takes an Int and returns an Int. The function body uses the map method to apply f to each element of numbers, returning a new sequence with the transformed values.
Functions as return values
In Scala, you can define functions that return other functions as their result. This allows you to create new functions with specialized behavior by partially applying parameters or selecting behavior based on runtime conditions.
Here's an example of defining a function that returns another function:
def createGreetingFunction(prefix: String): String => String =
(name: String) => s"$prefix, $name!"
// Example usage
val greetHello = createGreetingFunction("Hello")
val greetHi = createGreetingFunction("Hi")
val message1 = greetHello("Mary") // "Hello, Mary!"
val message2 = greetHi("John") // "Hi, John!"
In this example, we define a function named createGreetingFunction that takes a single parameter prefix of type String, and returns another function that takes a String parameter and returns a String. The returned function concatenates the prefix and the input name parameter with a comma and space in between.
In the example usage, we call createGreetingFunction twice to create two new functions, greetHello and greetHi, which prepend the strings "Hello" and "Hi" to their input arguments, respectively. We then call these functions with different input strings to produce two different output messages.