Explanation of "-" and "+" in "feature2 [-T1, -T2, + R] extends AnyRef`
"-" contravariant "+" covariant
You can read subtyping on this blog http://blogs.atlassian.com/2013/01/covariance-and-contravariance-in-scala/
In addition, the course also discusses functional scala cursor programming.
"-" allows you to subclass T, so it is limited to input, "+" allows you to return the supertype of T, so it is generic for output.
class SuperBase
class Base extends SuperBase
class SubBase extends Base
val add: Function1[Base, Base] = { base =>
new SubBase //ignore this
}
add(new SubBase) //ok
add(new SuperBase) //compilation fail
val result: SuperBase = add(new SubBase) //ok
val result: SubBase = add(new SubBase) //compilation fail
source to share
These are variance and covariance annotations that are used to define how a subtype relationship works for polymorphic types. For example, List[+A]
indicates that lists are covariant in content: if you have a type Dog
that is a subtype Animal
, then the type List[Dog]
will be a subtype List[Animal]
. In funny symbols: If you have types A<:B
and you have defined a type X[+T]
with a covariance type parameter T
, then X[A]<:X[B]
. "-" is used for contravariance, and it's hard for me to give an example of its use: in general, if A<:B
you also have a type X[-T]
, thenX[B] <: X[A]
... You might want to see coursera in programming languages, which I think explains this, and why functions are contravariant in their arguments and covariant in their results.
source to share