0

I started scala course on coursera, but I can't get one thing here:

trait Generator[+T] { self => // do this to be able to use self instead of this def generate: T def map[S](f: T => S): Generator[S] = new Generator[S] { def generate = f(self.generate) } } 

Why we are using map[S] not just map in function definition?

5
  • This is how a method with type parameters is defined in Scala. The method map has a type parameter, S. Commented Jun 4, 2015 at 14:45
  • 2
    You are mapping a Generator[T] to another Generator, not necessarely aGenerator[T], that's why you need to tell the compiler to the type you want to end up with. Commented Jun 4, 2015 at 14:46
  • Because you might want to create a Generator[String] from a Generator[Int], not just Generator[Int]s can be returned this way. You have to refer to the new generic parameters somehow. Commented Jun 4, 2015 at 14:47
  • I think the question is why is the type param S and not U. Commented Jun 4, 2015 at 15:16
  • Coursera has forums where you can ask the course TAs and the other students questions like this. They're probably in a better position to give a good answer since they're familiar with the specific code you're working with. Commented Jun 4, 2015 at 15:31

1 Answer 1

1

The [S] after map is a type parameter and makes it a so-called polymorphic method. In your example above, if you wrote the same def map, but without [S], the compiler wouldn't be able to tell what S is when encountering it in the remaining method definition. So the [S] makes the identifier S known to the compiler and puts it in the position to report typos as errors.

For example, assume a new method in which you accidentally wrote f: T => Floot rather than f: T => Float. What you want is the compiler to complain that Floot is an unknown identifier. You wouldn't want it to silently assume that Floot is some sort of type parameter.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.