When I write a function like def foo[A,B]
, what exactly does the [A,B]
mean? I know it's a Polymorphic Method; but when do you use foo [A]
versus foo [A,B]
?
Here's an example where I don't understand the difference. This function compiles:
def map[B](f: A => B): Stream[B] =
foldRight(empty[B])((h,t) => cons(f(h), t))
Whereas this one doesn't compile. I don't understand why the A
isn't required, after all A
is referenced by the f: A => B
:
def map[A,B](f: A => B): Stream[B] =
foldRight(empty[B])((h,t) => cons(f(h), t))
[error] ..../Stream.scala:61: type mismatch;
[error] found : h.type (with underlying type A)
[error] required: A
[error] foldRight(empty[B])((h,t) => cons(f(h), t))
(this is from one of the FP in Scala exercises)
Addendum
After reading the answers I'm adding some context, to help future readers. The function is defined inside a trait:
trait Stream[+A] {
...
def map[B](f: A => B):Stream[B] =
foldRight(empty[B])((h,t) => cons(f(h), t))
...
}
So the error was being caused by type shadowing, but see @acjay's excellent answer below.
Googling scala type shadowing
doesn't result in a direct definition in any of the scala docs, which is interesting because as @travisbrown says below, it's "one of the most common sources of beginner confusion I've seen". There is a discussion here: Why does Scala support shadow variables?