Search code examples
scalahigher-kinded-types

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...


Solution

  • 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.