I have a map where both the keys and values are generic types. Something like this:
Map[Foo[A], Bar[A]]
What I’d like to express is that the type A may be different for each key-value pair in the map, but every key is always parameterized with the same type as the value that it maps to. So a Foo[Int] always maps to a Bar[Int], a Foo[String] always maps to a Bar[String], and so forth.
Does anyone know a way to express this?
EDIT:
Here’s an example of the sort of thing I’m trying to do:
trait Parameter // not important what it actually does
class Example {
val handlers: Map[_ <: Parameter, (_ <: Parameter) => _] = Map()
def doSomething() {
for ((value, handler) <- handlers) {
handler(value)
}
}
}
The idea is that a value will always map to a function that can accept it as a parameter, but as the code is written now, the compiler can’t know this.
As it turns out, it is possible to define a heterogeneous map in Scala. Here’s a rough sketch:
This could be made completely typesafe by internally using a linked list of mappings instead of a map, but this is better for performance.
My original example would look like this:
This is almost perfect, except I’m not sure how to add bounds.