Search code examples
scalapartialfunction

Scala: Function definition of PartialFunction is ambiguous


Function definition of the PartialFunction is following:

trait PartialFunction[-A, +B] extends (A) ⇒ B

PartialFunction would allow us to filter by using case with collect on collection. For example when you have list of integers and PartialFunction isEven[Int, String] which will convert to String if the value in the collection is even number. So it returns a new collection with the return type +Bin the definition.

My question is, why contravariant -A and covariance +B? It basically has ability to accept any input to any output. Why do we need to indicate the input should be a any type or super type of a type A and return type should be B or its subclass? Can't we just say:

trait PartialFunction[A, B]

Solution

  • No, it does not "basically allow it to accept any input to any output". Co- and contravariance are not trivial (in the mathematical sense) relations, they are strictly defined by the bound type - as you probably realize.

    This specific form of type bounds, i.e. contravariance of arguments and covariance of the return type is a general phenomenon, not limited to Scala, and comes from the notion of function types from formal type theory, specifically:

    If T1 → T2 is a function type then a subtype of it is any function S1 → S2 with the property that T1 <: S1 and S2 <: T2.

    allowing for a well-defined subtyping relation of said function types.