Scala Tutorial
Basics
Control Statements
OOP Concepts
Parameterized - Type
Exceptions
Scala Annotation
Methods
String
Scala Packages
Scala Trait
Collections
Scala Options
Miscellaneous Topics
Anonymous functions, often referred to as lambda functions or simply lambdas in many programming languages, are functions that are defined without a name. Scala supports the use of anonymous functions, and they are frequently utilized in scenarios where a function is needed for a short period, often as an argument to higher-order functions.
Here's how you can define and use anonymous functions in Scala:
Basic Syntax:
The basic syntax of an anonymous function in Scala is (parameters) => body
.
val add = (a: Int, b: Int) => a + b println(add(5, 3)) // Outputs: 8
Using with Higher-Order Functions:
One of the most common use cases for anonymous functions is passing them as arguments to higher-order functions like map
, filter
, foreach
, etc.
val numbers = List(1, 2, 3, 4, 5) numbers.map(x => x * 2) // List(2, 4, 6, 8, 10)
Placeholder Syntax:
For simple anonymous functions, Scala allows the use of _
as a placeholder, which makes the function definition even more concise.
numbers.map(_ * 2) // Equivalent to the previous example
Multiple Placeholders: If you're using multiple parameters in your anonymous function, you can use multiple underscores to represent each parameter in order.
val pairs = List((1, 2), (2, 3), (3, 4)) pairs.map(_ + _) // List(3, 5, 7)
Type Inference: In many cases, Scala can infer the types of the parameters for you, so you don't have to specify them explicitly. However, sometimes, for clarity or ambiguity resolution, you might want to specify the types.
val strings = List("a", "ab", "abc") strings.filter(s => s.length > 1) // List("ab", "abc")
Block Body: For more complex logic, you can use a block body with your anonymous function.
val values = List(1, -2, 3, -4, 5) values.filter { x => val isPositive = x > 0 isPositive } // List(1, 3, 5)
As Function Arguments: Anonymous functions can also be passed directly as arguments to methods or functions without being assigned to a variable.
numbers.foreach(x => println(x))
In conclusion, anonymous functions are a powerful feature of Scala, enabling concise function definitions and facilitating functional programming techniques. They are especially valuable when working with collections, APIs that expect function arguments, or any context where short, one-off function logic is needed.
Anonymous functions vs. named functions in Scala:
// Named function def add(x: Int, y: Int): Int = x + y // Anonymous function (lambda) val addLambda: (Int, Int) => Int = (x, y) => x + y
Using anonymous functions as arguments in Scala:
val numbers = List(1, 2, 3, 4, 5) // Using anonymous function with map val squared = numbers.map(x => x * x)
Scala lambda expressions and anonymous functions:
// Lambda expression (anonymous function) val multiply: (Int, Int) => Int = (x, y) => x * y
Anonymous functions in Scala collections:
val numbers = List(1, 2, 3, 4, 5) // Anonymous function for filtering val evenNumbers = numbers.filter(x => x % 2 == 0)
Partial functions and anonymous functions in Scala:
val divide: PartialFunction[Int, Int] = { case x if x != 0 => 10 / x }
Scala higher-order functions and anonymous functions:
val numbers = List(1, 2, 3, 4, 5) // Higher-order function with anonymous function val doubled = numbers.map(x => x * 2)
Anonymous functions and closures in Scala:
def multiplier(factor: Int): Int => Int = { // Anonymous function (closure) x => x * factor } val multiplyByTwo = multiplier(2)
Pattern matching with anonymous functions in Scala:
val process: Int => String = { case 0 => "Zero" case even if even % 2 == 0 => "Even" case odd => "Odd" }
Anonymous functions in Scala's functional programming:
val numbers = List(1, 2, 3, 4, 5) // Using anonymous function with reduce val sum = numbers.reduce((x, y) => x + y)
Currying and anonymous functions in Scala:
// Curried function using anonymous functions val addCurried: Int => Int => Int = x => y => x + y
Anonymous functions in Scala Futures:
import scala.concurrent.Future import scala.concurrent.ExecutionContext.Implicits.global val futureResult: Future[Int] = Future { // Anonymous function for asynchronous computation 42 }