Jonathon Bell
Jonathon Bell

Reputation: 73

Bind type variable to element type of collection

How does one bind a polymorphic type variable to the parameter of a unary type constructor in Scala?

def f[CollectionOfE] = new Blah[...]
{
  def g(a: E) = 
  { ... } 
}

...

val x = f[Set[Int]]  // want E above to bind to Int

Within the definition of g i wish to be able to refer to the parameter type of the collection on which f has been instantiated.

I've tried:

def f[C[E]] = new Blah[...] ...

but the scope of E seems to be local to the [ ... ], if that makes any sense...

Upvotes: 1

Views: 90

Answers (2)

Haspemulator
Haspemulator

Reputation: 11308

If I understand your intention correctly, you might want something like this:

def f[E, C[_]] = new Blah[...] {
  def g(e: E) = ???
}

...

f[Int, Set]

Basically, if you want to refer to a type later, you need to put it as a separate type parameter. You might also want to limit type of C[_] to some collection.

Upvotes: 0

Chris C
Chris C

Reputation: 229

You can do this if you define E a separate parameter. E.g.

def f[E, C <: util.Collection[E]] = new Blah  {
   def g(a: E) = ...
}

val x = f[Int, Set[Int]].g(1)  // compiles

val y = f[Int, Set[Int]].g("string")  // doesn't compile

Edit You can make it slightly more concise by calling the function with underscore:

f[Int, Set[_]].g(1)

Upvotes: 1

Related Questions