contravariance confusion resolved

Previous Topic Next Topic
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
Report Content as Inappropriate

contravariance confusion resolved

I think I finally understand why Function1 trait has a contravariant type parameter, after not understanding several explanations. I thought I would share what I was being confused about in case it is interesting to anyone or in case I demonstrate that I didn't actually understand.

Here is an example from programming in scala:

 class Publication(val title: String)
  class Book(title: Stringextends Publication(title)

  object Library {
   val books: Set[Book] =
       new Book("Programming in Scala"),
       new Book("Walden")
   def printBookList(info: Book => AnyRef) = {
     for (book <- books) println(info(book))

  object Customer extends App {
   def getTitle(p: Publication): String = p.title

Part of the explanation is:

Because any method declared in Publication is also available on its subclass Book, everything should work, which is what contravariance of function parameter types means

Each time I read an explanation like this, I was baffled, because I thought that it is demonstrating the opposite, that a parameter declared as Publication can be set from a sub-class of Publication.

I think it would be easier for people to understand if the explanation showed that the fact that the type parameter allows a super-class to be supplied means that the implementation accepts instances of a subclass of it's parameter's type and that there is potential confusion because variance in opposite directions is being described.

You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.