0

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]
1
  • 1
    By the way, this rule of covariance/contravariance in functions holds not only in scala. Commented Jun 12, 2014 at 14:07

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

My question is for partial function, why co-contra variances were noted as is. Some example would be helpful.
For exactly the same reason as non-partial functions. Why would you expect them to be different?
@Mayumi : exactly as Alexey said. Or do you need a general example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.