Functional programming methods in Scala are a set of higher-order functions that allow you to work with collections in a functional and declarative style. These methods are defined on various collection types (e.g., lists, sets, maps) and provide powerful ways to perform transformations, filtering, aggregations, and more without mutating the original collections. Here are some commonly used functional programming methods in Scala:
map:
Transforms each element of a collection by applying a given function to it.
val numbers = List(1, 2, 3)
val doubled = numbers.map(_ * 2) // Result: List(2, 4, 6)
filter:
Returns a new collection containing elements that satisfy a given predicate.
val numbers = List(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter(_ % 2 == 0) // Result: List(2, 4)
flatMap:
Applies a function to each element and flattens the results into a single collection.
val words = List("hello", "world")
val letters = words.flatMap(_.toList) // Result: List('h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd')
foldLeft and foldRight:
Combines elements of a collection using an associative binary operator.
val numbers = List(1, 2, 3, 4, 5)
val sum = numbers.foldLeft(0)(_ + _) // Result: 15
reduceLeft and reduceRight:
Similar to foldLeft and foldRight, but without an initial value. The first element is used as the starting value.
val numbers = List(1, 2, 3, 4, 5)
val product = numbers.reduceLeft(_ * _) // Result: 120
groupBy:
Groups elements of a collection based on a given function and returns a map where the keys are the function's results.
val words = List("apple", "banana", "cherry", "date")
val groupedByLength = words.groupBy(_.length)
// Result: Map(5 -> List(apple, banana, cherry), 4 -> List(date))
zip:
Creates pairs of elements from two collections based on their positions.
val numbers = List(1, 2, 3)
val letters = List('a', 'b', 'c')
val pairs = numbers.zip(letters) // Result: List((1, 'a'), (2, 'b'), (3, 'c'))
These functional programming methods provide expressive ways to manipulate collections in a functional style, making your code more concise, readable, and maintainable. By avoiding mutable state and side effects, you can improve the clarity and reliability of your code.