how to make anonymous function in scala

In Scala, you can create an anonymous function using the syntax (parameters) => expression. Here's an example:

val addOne = (x: Int) => x + 1
println(addOne(5)) // Output: 6

In the example above, addOne is an anonymous function that takes an integer x as a parameter and returns x + 1. The function is assigned to the variable addOne. You can then call the function using the variable name followed by the parameter in parentheses.

You can also create anonymous functions without explicitly specifying the parameter types, as long as the compiler can infer them:

val multiplyByTwo = (x: Int) => x * 2
println(multiplyByTwo(3)) // Output: 6

In this example, the parameter type is not explicitly specified, but the compiler can infer that x is of type Int based on the usage.

Anonymous functions can also have multiple parameters:

val add = (x: Int, y: Int) => x + y
println(add(2, 3)) // Output: 5

In this case, the anonymous function add takes two parameters x and y, and returns their sum.

You can use anonymous functions in various scenarios, such as passing them as arguments to higher-order functions or using them as concise alternatives to defining named functions.