I'm trying to achieve the following in scala and this seems to be beyond my "generic" skills:
I have 2 generic classes :
class A[T]
class B[T]
and I want to map some As to some Bs:
val m = Map[A, B]
Now that doesn't compile because A and B are generic, so
val m = Map[A[_], B[_]]
I want to be able to store A/B pairs for arbitrary types T. However I only want to add pairs for which the generic type is the same for the key and the value. So I can do
m updated(new A[String], new B[String])
but not
m updated(new A[String], new B[Int])
And I want the compiler to be aware of this so I can do
val a = new A[String]
val b = new A[String]
val m = Map(a -> b)
val b: B[String] = m(a) //
I was thinking a library like shapeless could help ?
I think this enforces the restrictions you're after.
class A[T]
class B[T]
val as = new A[String]
val bs = new B[String]
val ai = new A[Int]
val bi = new B[Int]
val ms: Map[A[X], B[X]] forSome {type X}= Map(as -> bs) // OK
val mi: Map[A[X], B[X]] forSome {type X}= Map(ai -> bi) // OK
No other combinations of as
, bs
, ai
, and bi
will compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With