Anonymous functions in Scala

In Scala, anonymous functions are functions that are defined without a name. Anonymous functions are also known as lambda functions or function literals. They are often used as arguments to higher-order functions, or to create simple one-off functions.

Anonymous functions in Scala are defined using the following syntax:

scala
(parameters) => expression

The `parameters` represent the input parameters to the function, and the `expression` represents the computation that the function performs. For example, the following anonymous function takes an integer `x` as input, and returns the square of `x`:

scala
val square = (x: Int) => x * x

In this example, the anonymous function has a single parameter `x` of type `Int`, and returns the result of multiplying `x` by itself.

Anonymous functions can also be used with higher-order functions like `map()` and `filter()`. For example, the following code uses an anonymous function to filter out all the even numbers from a list of integers:

scala
val numbers = List(1, 2, 3, 4, 5)
val oddNumbers = numbers.filter((x: Int) => x % 2 != 0)

In this example, the anonymous function takes a single input parameter `x` of type `Int`, and returns `true` if `x` is odd (i.e., if its remainder when divided by 2 is not 0).

Scalaalso supports shorthand syntax for defining anonymous functions, called “underscore syntax”. This syntax can be used when the input parameters and return type of the function can be inferred from context. For example, the following code defines an anonymous function using underscore syntax:

scala
val numbers = List(1, 2, 3, 4, 5)
val oddNumbers = numbers.filter(_ % 2 != 0)

In this example, the underscore character is used to represent the input parameter to the function. Because the `filter()` function expects a function that takes a single input parameter of type `Int`, the compiler can infer that the underscore represents an `Int` parameter.

Overall, anonymous functions are a powerful feature of Scala that allow for concise and expressive code, particularly when combined with higher-order functions and underscore syntax.