Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Map with generic classes as Key/Value types

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 ?

like image 754
user1498572 Avatar asked Mar 10 '23 19:03

user1498572


1 Answers

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.

like image 77
jwvh Avatar answered Mar 13 '23 05:03

jwvh