Explain the Scala Anonymous Function

Category : Scala | Sub Category : Scala Interview Questions | By Prasad Bonam Last updated: 2023-09-27 09:17:44 Viewed : 330


 Explain the Scala Anonymous Function:

In Scala, an anonymous function is a function that is defined without a name. It is also known as a lambda function or a function literal. Anonymous functions are a fundamental feature of functional programming in Scala and are used for concise and lightweight function definitions. They are often used in situations where you need to pass a function as an argument to another function or define small, short-lived functions.

Here is the basic syntax for defining an anonymous function in Scala:

scala
(parameters) => expression
  • parameters: These are the input parameters or arguments to the function. You can have zero or more parameters. If there are multiple parameters, they are enclosed in parentheses.

  • =>: The "rocket" symbol (=>) separates the parameter list from the expression that defines the functions behavior.

  • expression: This is the body of the function, which is a single expression that calculates and returns a value.

Here is an example of a simple anonymous function that adds two numbers:

scala
val add = (x: Int, y: Int) => x + y

In this example, add is an anonymous function that takes two integer parameters x and y and returns their sum. You can use this anonymous function just like any other function:

scala
val result = add(3, 5) // result is 8

Anonymous functions can also be assigned to variables, passed as arguments to other functions, and returned from functions. Her is an example of passing an anonymous function as an argument to the map function:

scala
val numbers = List(1, 2, 3, 4, 5) val doubledNumbers = numbers.map((x: Int) => x * 2)

In this example, we use an anonymous function to double each element in the list when calling the map function.

Anonymous functions are concise and convenient for simple operations. However, for more complex functions, you may prefer to define named functions using the def keyword for better readability and reusability. Nevertheless, anonymous functions are a powerful tool in Scala is functional programming toolkit and are commonly used in conjunction with higher-order functions like map, filter, and reduce to express transformations and computations concisely.


Search
Related Articles

Leave a Comment: