Ariel T Ariel T - 4 years ago 100
Scala Question

+- Signs in Generic Declaration in Scala

I was looking at the documentation for PartialFunction in this link:

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

Maybe someone can help clarify the significance of the plus and minus signs in the generic declaration?

Answer Source

"+" and "-" means covariant and contravariant types respectively. In short, it means that:

PartialFunction[-A1, +B1] <: PartialFunction[-A2, +B2] only if A1 :> A2 and B1 <: B2,

where <: is subtyping relationship.

"-" usually applied for input parameters, "+" for output - in C# they even use respective keywords in and out. By default (without modifiers) PartialFunction[A1, B1] has no direct relationship to the PartialFunction[A2, B2] (in other words, it's invariant).

There is also some restrictions, like covariant("+") type can't be in contravariant position (you can only return it from functions) and vice-versa. This is done to support Liskov Substitution Principle and naturally understandable by "in"/"out" interpretation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download