0

I am diving in FP concepts using Scala. I think that I've finally understood what covariance and contravariance are and why function types are contravariant in their argument types and covariant in their return types. But there is still somethig that I don't understand. In Scala, a List[+A] has a prepend (+:) method that takes an S where S >: A. If the type was an A, the compiler would throw an error: covariant parameter in contravariant position, I don't understand why the fact of declaring a List[+A] makes A covariant in the function definition. As far as I understand, covariance and contravariance relates to more complex types than A, that is, monads or functions.

Scala list: http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.List

Maxim
  • 1,209
  • 15
  • 28
vicaba
  • 2,836
  • 1
  • 27
  • 45
  • 2
    Take a look here: http://stackoverflow.com/questions/9619121/why-is-parameter-in-contravariant-position. I think, it answers your exact question. – Dima Dec 07 '15 at 20:38
  • @Dima The question I have is neither about the "error" nor the reason why it is this way but why A is covariant in the function. As I understand, C[+T] does something with C subtyping in relation to its parametrized type and not with the parametrized type itself. I don't know how to say it in other words... – vicaba Dec 07 '15 at 22:21
  • 1
    the wording of the error message is somewhat confusing. A is not really covariant or contravariant. The correct way to put it is that `List[+A]` is covariant in type `A`. On the other hand `+:(S)` is contavariant in `S`, and the meaning of the error message is that the same type cannot appear in both co- and contravariant position at the same time. – Dima Dec 08 '15 at 00:20
  • 1
    Similar question about example of variance positions: http://stackoverflow.com/a/12452506/1296806 – som-snytt Dec 08 '15 at 04:45
  • @Dima That's the answer I was looking for :). som-snytt answer also gives light to my question – vicaba Dec 08 '15 at 10:27

0 Answers0