How does Scala support 'Functional Programming'?

Instruction: Explain the features and principles of functional programming that Scala supports.

Context: This question aims to evaluate the candidate's understanding of how Scala blends object-oriented and functional programming paradigms, including its support for first-class functions, immutability, higher-order functions, and how these features facilitate functional programming.

Updated

Scala supports functional programming through first-class function values, higher-order methods, immutable collections, algebraic data models and pattern matching. A function can be passed into another function or returned as a result; transformations such as map, filter and foldLeft make that useful for ordinary data processing.

final case class Item(name: String, quantity: Int)
def namesInStock(items: List[Item]): List[String] =
  items.filter(_.quantity > 0).map(_.name)

@main def functionalExample(): Unit = {
  val inventory = List(Item("pen", 2), Item("book", 0))
  assert(namesInStock(inventory) == List("pen"))
  assert(inventory == List(Item("pen", 2), Item("book", 0)))
}

This transformation is pure: its result depends on its input and it does not change external state. Pure functions are easier to test in isolation and substitute with their results. Sealed traits or enums and case classes model alternatives and data; Option and Either make absence or expected errors explicit. For-comprehensions provide syntax for operations supported by the participating types. Pure functions

Scala also allows mutation, exceptions, inheritance and I/O. Functional style is a design choice, not a language guarantee. A val can reference mutable data, a callback can throw, and immutable data does not make every surrounding concurrent workflow safe. Keep business transformations pure where practical and place database, network and other effects behind explicit boundaries.

Related Questions