Explain the concept and practical use of Partial Functions in Scala.

Instruction: Describe what Partial Functions are and provide a practical example of their use in Scala applications.

Context: This question assesses the candidate's understanding of Partial Functions in Scala, including their definition, use cases, and how they can be utilized in real-world scenarios.

Updated

A PartialFunction[A, B] describes a transformation defined for only part of the input domain. isDefinedAt reports whether an input belongs to that domain. This differs from a partially applied function, where some arguments have been supplied already.

val positiveSqrt: PartialFunction[Int, Double] = {
  case x if x > 0 => math.sqrt(x)
}
@main def partialFunctionExample(): Unit = {
  val numbers = List(-3, -1, 0, 4, 10)
  val result = numbers.collect(positiveSqrt)
  assert(result == List(2.0, math.sqrt(10.0)))
  assert(!positiveSqrt.isDefinedAt(0))
  assert(positiveSqrt.lift(-1) == None)
  assert(positiveSqrt.lift(4) == Some(2.0))
  val includingZero = positiveSqrt.orElse { case 0 => 0.0 }
  assert(includingZero(0) == 0.0)
  assert(includingZero.lift(-1) == None)
}

collect selects defined inputs and transforms them. lift exposes absence as an Option; orElse supplies another partial domain and uses the first matching function. The example intentionally excludes zero until that fallback is added. Partial function operations

The guard does not prevent a caller from writing positiveSqrt(-1): directly applying this literal outside its domain throws MatchError. Prefer collect, lift or applyOrElse when undefined inputs are expected. Keep guards and transformations predictable; a separate isDefinedAt check followed by application can repeat work or observe changed state. A defined case can still throw within its body; lift is not a general exception-catching mechanism. Partial functions

Related Questions