WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Scala · Basic · question 17 of 100

What is a Partial Function in Scala, and how does it differ from a total function?

📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

In Scala, a Partial Function is a function that is only defined for certain input values and may not produce a valid output for all possible inputs. A Total Function, on the other hand, is a function that produces a valid output for any input value within its domain.

Let’s dive into more details for each type of function:

1. Total Function:

A total function is a function that is defined for every input value in its domain. In other words, for every input x in the domain of the function, it must provide a corresponding output value y. Mathematically, a total function can be represented as:


f : A → B

where A is the domain of the function, B is the codomain, and f is the total function. For instance, in Scala, a simple total function could be:

val totalFunction: Int => Int = x => x * 2

In this example, the function is defined for every ‘Int‘ input and returns its double as output.

2. Partial Function:

A partial function is a function that is defined for only a subset of its domain. It is incapable of processing every input value within its domain. Mathematically, a partial function can be represented as:


f : A_subset → B

where A_subset is the subset of the domain A, and f is the partial function.

In Scala, a partial function is represented using the ‘PartialFunction‘ trait. It inherits from the ‘Function‘ trait and adds the ‘isDefinedAt‘ method, which checks if the given input lies within the defined subset of the domain.

Here’s an example of a partial function that only processes positive integers:

val partialFunction: PartialFunction[Int, Int] = {
  case x if x > 0 => x * 2
}

This partial function will only process positive integers and double them. For other integers, the function is not defined, and using it on such inputs will result in an exception. You can check if a value is within the defined domain using the ‘isDefinedAt‘ method:

partialFunction.isDefinedAt(-1) // Returns false
partialFunction.isDefinedAt(5) // Returns true

In summary, the main difference between a total function and a partial function in Scala is their defined domain. A total function is defined for all input values within its domain, while a partial function is only defined for a subset of its domain.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Scala interview — then scores it.
📞 Practice Scala — free 15 min
📕 Buy this interview preparation book: 100 Scala questions & answers — PDF + EPUB for $5

All 100 Scala questions · All topics