Skip to content

Instantly share code, notes, and snippets.

Exploring Type-Safe Dynamic Maps in Scala 3

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.

What is a Heterogeneous Map?

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

import scala.annotation.implicitNotFound
import scala.language.{dynamics, implicitConversions}
object HMap:
opaque type M[T <: Tuple] = Map[Any, Any]
extension [T <: Tuple](m: M[T])
def add[K <: Singleton, V](k: K, v: V)(using
NoMatch[T, K] =:= true
): M[(K, V) *: T] = m + (k -> v)