Sławosz
Sławosz

Reputation: 11697

Scala syntax which I don't understand

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?

Upvotes: 0

Views: 95

Answers (1)

tossbyte
tossbyte

Reputation: 380

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.

Upvotes: 1

Related Questions