How to implement type-safe heterogeneous containers in Scala?
Instruction: Provide an example implementation of a type-safe heterogeneous container using Scala features.
Updated
For a heterogeneous container whose layout is known at compile time, Scala 3 tuples retain a separate type for each element. They are more precise than a List[Any] and do not require caller-side casts for typed positions.
def prepend[H, T <: Tuple](head: H, tail: T): H *: T = head *: tail
@main def heterogeneousExample(): Unit = {
val record: (Int, String, Boolean) = (7, "Ava", true)
val id: Int = record.head
val name: String = record.tail.head
val active: Boolean = record.tail.tail.head
val expanded: (Double, Int, String, Boolean) = prepend(1.5, record)
assert(id == 7 && name == "Ava" && active)
assert(expanded.head == 1.5)
assert(expanded.tail == record)
}
H *: T expresses a tuple with a head of type H followed by the tuple T; EmptyTuple is the empty base. The generic prepend preserves the tail's types. Assigning record.tail.head to an Int is a compile-time error. Typed tuple operations
This solves a statically known heterogeneous sequence. Two separate homogeneous boxes do not, by themselves, demonstrate one heterogeneous container. A dynamic registry needs a different contract, such as typed keys with a carefully encapsulated association between key and stored value; a Map[String, Any] followed by an unchecked cast does not establish that contract.
Keep the tuple's precise type in APIs when callers need typed positions. Widening it to a general Tuple, iterating through runtime elements, or selecting with an unknown runtime index can lose per-position static information. A case class is often clearer when the fields have stable domain names. Neither representation validates business constraints or makes nested mutable objects immutable.