user79074
user79074

Reputation: 5280

Converting set of parameterized types to a map

Can someone maybe explain to me why I get a compiler error below and the best way to do this type of conversion

Thanks Des

case class A[T](i: Int, x: T)
val set: Set[A[_]] = Set(A(1, 'x'), A(2, 3))
val map: Map[Int, A[_]] = set.map(a => a.i -> a)

type mismatch; found : scala.collection.immutable.Set[(Int, A[_$19]) forSome { type _$19 }] required: Map[Int,A[_]]

Upvotes: 0

Views: 36

Answers (1)

Ende Neu
Ende Neu

Reputation: 15783

There are a couple of things here, first I suppose that A is a case class (otherwise you would need to use the new keyword), second your map returns a Set of tuples (not a Map), third you are returning a A[_] in the map, but a.x returns an Any, not an A:

scala> case class A[T](i: Int, x: T)
defined class A

scala> val set: Set[A[_]] = Set(A(1, 'x'), A(2, 3))
set: Set[A[_]] = Set(A(1,x), A(2,3))

To match the type signature you can use toMap and change Map[Int, A[_]] to Map[Int, _]

scala> val map: Map[Int, _] = set.map(a => a.i -> a.x).toMap
map: Map[Int, _] = Map(1 -> x, 2 -> 3)

If you want to keep the original signature (Map[Int, A[_]]) you need to return an A in the tuple:

scala> val map: Map[Int, A[_]] = set.map(a => a.i -> a).toMap
map: Map[Int,A[_]] = Map(1 -> A(1,x), 2 -> A(2,3))

Upvotes: 2

Related Questions