Get key and value types of scala map

81 Views Asked by At

If I have a complicated map type, like

type MyMap = Map[(String, String), List[Map[String, Int]]]

is there a way to do something like Map.Key to get the type of the key (here, (String, String))?

I expect the standard answer is to either declare classes that are the key and value types, or use

type MyMapKey = (String, String)
type MyMapValue = List[Map[String, Int]]
type MyMap = Map[MyMapKey, MyMapValue]

In this case, I'm using MyMap in many places, but only using the key and value types in one place that prepares data for use with the map. So the key and value types feel like implementation details that don't need names at the same level as MyMap.

It is a common feature in other languages with an expressive type system, so I was expecting to find it in Scala, but it does not seem to be there.

I am using Scala 3 if that matters.

1

There are 1 best solutions below

0
On BEST ANSWER

In Scala 3 you can use match types

type Key[M] = M match
  case Map[k, _] => k

or

type Key[M <: Map[?, ?]] = M match
  case Map[k, _] => k

Testing:

implicitly[Key[MyMap] =:= (String, String)]

https://docs.scala-lang.org/scala3/reference/new-types/match-types.html