Brad Collins (20) [Avatar] Offline
#1
I accidentally left off the [A] from the startsWith declaration. In other words, I typed

def startsWith(s: Stream[A]): Boolean


instead of

def startsWith[A](s: Stream[A]): Boolean



The compiler issues the following error:

covariant type A occurs in contravariant position in type ch05.Stream[A] of value s

startsWith is a method of trait Stream[A]. Why is the type parameter necessary for this declaration? Why is it not assumed/inferred? I am apparently missing something about how covariance vs. contravariance comes into play here.
runar (53) [Avatar] Offline
#2
Re: Why does startsWith need a type parameter? (Exercise 5.14)
If you want `Stream` to be covariant in its element type `A`, then you need:

def startsWith[B >: A](s: Stream[B]): Boolean

See the chapter notes for more information on variance:

https://github.com/fpinscala/fpinscala/wiki/Chapter-4:-Handling-errors-without-exceptions#covariance-and-contravariance

Message was edited by:
runar