Explanation of "-" and "+" in "feature2 [-T1, -T2, + R] extends AnyRef`

What are the purposes and definitions of "-" and "+" used for input and return types in feature signature such as trait Function2[-T1, -T2, +R] extends AnyRef

Can anyone suggest the exact location in the spec to read about this?

+3


source to share


2 answers


"-" 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

      

+2


source


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.



+3


source







All Articles