In this blog post, we'll dive into a powerful implementation of a type-safe heterogeneous map in Scala 3. We'll explore how to create a TypedHMap
(a slight twist on the original HMap
name) that allows keys and values of different types while maintaining type safety, and pair it with a dynamic interface for an intuitive, case-class-like experience. Along the way, we'll unpack the Scala 3 concepts that make this possible and showcase its power with practical examples.
In Scala, a standard Map
requires all keys to share one type (e.g., String
) and all values to share another (e.g., Int
), as in Map[String, Int]
. But what if you need a map where each key-value pair can have its own types—like "name" -> String
, "age" -> Int
, and "active" -> Boolean
—all within the same map? This is where a heterogeneous map comes in. Unlike a Map[Any, Any]
, which sacrifices type safety, our goal is a map that enforces type correc