Category : Scala | Sub Category : Scala Interview Questions | By Prasad Bonam Last updated: 2023-09-26 23:50:19 Viewed : 274
Functional collections in Scala are collections that emphasize and encourage functional programming principles. They provide a set of operations and transformations that allow you to work with collections in a functional and immutable way. Scalas standard library includes a rich set of functional collections that promote immutability, concise code, and expressive data transformations. Here are some key functional collections in Scala:
List:
Scalas List
is a functional collection that represents an ordered, immutable, and linked list. You can perform operations like map
, filter
, reduce
, and others in a functional style.
scalaval myList = List(1, 2, 3, 4, 5) val doubledList = myList.map(_ * 2)
Seq (Sequence):
Seq
is a trait that represents a sequence of elements. It includes both List
and Vector
, among others, as concrete implementations. Seq
provides a functional API for working with sequences.
scalaval mySeq = Seq(1, 2, 3, 4, 5) val squaredSeq = mySeq.map(x => x * x)
Set:
Scalas Set
is an immutable collection that represents an unordered set of distinct elements. You can perform set operations like union
, intersection
, and difference
in a functional way.
scalaval set1 = Set(1, 2, 3) val set2 = Set(2, 3, 4) val unionSet = set1.union(set2)
Map:
Map
is a functional collection representing a collection of key-value pairs. You can use functional operations to transform and manipulate maps.
scalaval myMap = Map("Alice" -> 25, "Bob" -> 30, "Carol" -> 28) val ageAfterBirthday = myMap.map { case (name, age) => (name, age + 1) }
Option:
While not a traditional collection, Option
is a functional type in Scala used to represent optional values. It can contain either Some
value or None
. It encourages safe handling of potential absence of values.
scalaval maybeValue: Option[Int] = Some(42) val doubledValue = maybeValue.map(_ * 2)
Functional collections in Scala promote immutability and provide methods that return new collections instead of modifying the existing ones. This allows for safer and more predictable code in concurrent and parallel scenarios. Functional programming with collections is a powerful paradigm in Scala that helps developers write concise and expressive code while maintaining code correctness and safety.