One of the most distinctive aspects of Scala 3 is the way it elevates the compiler from a conservative static checker into a powerful reasoning engine. With features like inline computation, macros, match types, and generally a more expressive system for contextual abstractions, Scala 3 allows developers to push significant logic and validation into compile time, far beyond what mainstream languages such as Java, C# or Kotlin could offer in their vanilla form.
This technical facet doesn’t just change how programs are verified, it changes how they are written. Patterns that once required runtime checks using third-party libs or writing boilerplate can now be encoded as type‑level evidence, guiding developers toward lighter, much more correct designs through the type system itself.
Before diving in, let’s briefly outline what this lecture aims to uncover:
- We’ll examine how these capabilities for encoding evidence shape everyday coding practices, influence developer productivity and reasoning, and inform the broader engineering mindset, both at the application level and in the design of reusable libraries.
- More importantly, we’ll rethink what evidence means in Scala 3 by exploring not only its canonical form (typeclass‑style contextual abstractions), but also alternative mechanisms (such as runtime-assistance, inline logic, pattern-matching, and compile‑time metaprogramming) for implementing the same idea.
- We’ll examine a meaningful categorization of the evidence produced, and made visible, by the deeper structural patterns shared across these different implementation approaches.
Evidence Categorization
Our first step before we move deeper into the mechanisms themselves, it’s addressing the question of categorization. This comes in handy because once we begin examining how evidence is implemented in practice, a deeper pattern emerges, one that is helpful to recognize beforehand so you know what to expect and how to reason about it during code design and analysis.
You see, evidence doesn’t influence Scala code in a single uniform way, instead, it manifests through two distinct modes of interaction that developers repeatedly encounter in both application‑level logic and library‑level design. These modes aren’t official language constructs, but they arise naturally from how Scala 3’s type system collaborates with the compiler and, at times, how it interacts with runtime information.
Scala 3’s type system doesn’t merely describe programs, it actively participates in building and validating them. Once you begin relying on type‑level evidence (canonical or not), you encounter its influence in two distinct ways during the act of writing Scala code. This happens whether or not the evidence operates purely at compile time or it also cooperates with runtime checks.
So, without further ado, here they are:
Blocking evidence 🛡️
In most cases evidence is used in a defensive way, it acts as a barrier that prevents misuse.
When a required piece of evidence cannot be summoned, the compiler stops you immediately.
This mode of use protects APIs from being called with the wrong types, prevents incompatible abstractions from being combined, and enables enforcing domain rules directly at compile time.
This is the stop right here form of evidence, development halts long before runtime.Refinement evidence 🔍
This form of evidence is used constructively, it gives the compiler additional information so it can refine types inside a block of code.
Developers typically invoke it consciously to eliminate ambiguity, guide type inference, and enable precise logic.
So in contrast to the other one, this evidence doesn’t block code, instead, it signals to the engineers, right in the flow of development, that they’re empowered to write logic the compiler can and will reason about more deeply.
Together, the blocking and refinement modes of evidence are part of those elements that shape the way Scala developers structure their code, design robust APIs, and express domain models with precision.
Scala's Mainstream Evidence
To get a better feel for type‑level evidence, let’s begin by taking a closer look at the well‑known =:= class, the mainstream equality evidence which itself builds upon the <:< class, the mainstream subtype evidence.
Scala’s =:= type is the most popular tool for expressing blocking evidence. Its design is intentionally narrow and restrictive. Here are its main characteristics that define its purpose:
It is a sealed abstract class, so users cannot extend or instantiate it.
Its companion object, inherited from
<:<, exposes only a singleton, presented through a controlled cast. So the only available evidence is the trivialA =:= A, produced by thereflmethod.Because its type parameters are invariant,
A =:= Bcan only exist when A and B are exactly the same type.
This design ensures that equality evidence is created exclusively by the compiler and only when the types genuinely match. If they do not, the evidence cannot be summoned and the call site fails immediately, basically the essence of "blocking" behavior.
Applying Equality Evidence
Before we proceed, it’s worth noting that each of the concepts we’ll explore next will be grounded with small, concrete examples drawn from an application‑level project in the Passive‑haus domain. These examples will help clarify how Scala’s compile‑time evidence works in practice and how it contrasts with more traditional approaches.
Imagine we’re modeling the thermal envelope of a passive house. One of the operations we might have to support is increasing the total insulation thickness by laminating together two insulation layers of the same kind.
To begin, we need to define types for representing the structures of the issue we need to resolve and we need to define the unit types they'll be working with.
As you move through the article, additional units will appear, and some of the existing types will gain new functionality and dependencies.
For now, we'll start with a simple unit type used to represent insulation thickness. I’m introducing this one first so you can see what a simple unit type looks like. Later, I’ll also show you how a compound unit type is structured. To avoid cluttering the article with similar unit type definitions, I will show only one example of a simple unit type and one of a compound unit type. If you want to check out every unit type in full, including their operator‑based dependencies and other functionalities, you can find them all in the LayerUnits file.
package passivhaus.envelope.units
import scala.annotation.targetName
object Meter:
opaque type Meter = Double
@targetName("meterApply")
def apply(value: Double): Meter =
require(value > 0, s"Length must be positive, got $value")
value
extension (m: Meter)
@targetName("meterValue")
private[units] def value: Double = m
@targetName("meterMeterPlus")
def +(other: Meter): Meter = m + other
@targetName("meterDoubleScalarProduct")
def *(scalar: Double): Meter = m * scalar
@targetName("meterMeterGreaterThan")
def >(other: Meter): Boolean = m > other
@targetName("meterMeterLessThan")
def <(other: Meter): Boolean = m < other
extension (scalar: Double)
@targetName("scalarMeterProduct")
def *(m: Meter): Meter = m * scalar
To keep our units grouped by domain specificity, organized and easy to import, we’ll create separate objects named after their respective domain areas, that expose only the units relevant to that part of the model.
Through the rest of the project we'll import units through these domain‑focused export objects. These objects live in the same package as the unit definitions, but, for clarity, they’re located inside UnitExtensions file.
Alright, here’s the code we have so far for this:
package passivhaus.envelope.units
object LayerThickness:
export passivhaus.envelope.units.Meter.*
export passivhaus.envelope.units.Meter
Next, in LayerMaterials file we define the material types and the insulation representation:
package passivhaus.envelope.materials
import passivhaus.envelope.units.LayerThickness.*
trait Material
enum PassivhausCertifiedMaterial extends Material:
case WoodFiber
case MineralWool
case Cellulose
final case class Insulation[A <: PassivhausCertifiedMaterial](material: A, thickness: Meter)
Now, inside InsulationLamination, let’s take a look at how we might implement the lamination operation using compile‑time evidence.
Here is the type-level evidence‑based blocking version:
package passivhaus.envelope.thermal
import passivhaus.envelope.materials.*
object InsulationLamination:
def laminateLayers[
A <: PassivhausCertifiedMaterial,
B <: PassivhausCertifiedMaterial
] (
topLayer: Insulation[A],
bottomLayer: Insulation[B]
)(using sameTypeEvidence: A =:= B): Insulation[A] =
/*
Safe to proceed: in call-sites, reaching this point means the evidence has not blocked the flow
and it validated the type constraint at compile-time, so A == B is guaranteed.
*/
Insulation(
material = topLayer.material,
thicknessM = topLayer.thicknessM + bottomLayer.thicknessM
)
What advantages does this bring? Well:
- The compiler enforces the constraint A = B and guarantees it inside the guarded code-block
- No runtime checks are needed
- No reflection is involved
- Misuse is prevented during development, not after deployment
- The return type is exactly
Insulation[A], preserving full type precision
This is the blocking role of type‑level evidence. It stops invalid states from being representable at all, enforcing correctness before the program can even run. And this is actually a pretty common way user-devs leverage evidence, so expect me to bring it up quite often 🙃.
Alternatives to Compile-Time Evidence
Without any form of compile‑time evidence, there are essentially two broad approaches (both of which are basically just Java haircuts, pretty standard baseline in Java‑style codebases 😉):
- Push all the responsibility onto the user of your code. This means the user of your API must manually ensure that the materials match before calling the function. This increases the cognitive load on every caller and makes misuse far more likely.
- Perform validation at runtime. In order to preserve the type information of the result, an ADT will be used to store that. This is safer than the first approach, but it introduces boilerplate, runtime overhead, and the possibility of late‑failing errors at the user side of the deal as in the end the result, be it a success or not, is passed to the user to handle. InsulationLaminationRuntime, there is how such a version might look like:
package passivhaus.envelope.thermal.runtime
import passivhaus.envelope.materials.*
/*
This ADT preserves type info. Although necessary given the situation, it adds complexity and boilerplate code.
*/
enum LaminatedLayer:
case Success[A <: PassivhausCertifiedMaterial](layer: Insulation[A])
case MaterialMismatch(
top: PassivhausCertifiedMaterial,
bottom: PassivhausCertifiedMaterial
)
object InsulationLamination:
def laminateLayers(
topLayer: Insulation[?],
bottomLayer: Insulation[?]
): LaminatedLayer =
/*
Runtime will support validation this time. Depending on the complexity of the constraints this could be
resource expensive, but it could also be relatively cheap if the constraints are simple and straight-forward.
*/
val sameMaterialType =
topLayer.material.getClass == bottomLayer.material.getClass
if (!sameMaterialType)
/*
In here the responsibility for failure is passed down to the user.
This could involve further use of logging and error handling logic in the application, which would
make use of even more resources.
This is susceptible to human error so it can pass by being unhandled or handled inappropriately.
*/
LaminatedLayer.MaterialMismatch(
topLayer.material,
bottomLayer.material
)
else
/*
Type precision is retained through the ADT.
*/
LaminatedLayer.Success(
Insulation(
material = topLayer.material.asInstanceOf[topLayer.material.type],
thicknessM = topLayer.thicknessM + bottomLayer.thicknessM
)
)
Even in this small example, the difference in verbosity and clarity is obvious.
So, let’s make clear once more why this version is inferior by briefly walking through the above applied example:
- If the developers are negligent, errors in the form of the mismatch case surface at runtime rather than compile time. They may or may not be caught in the testing phase. If not caught then they can propagate further, possibly leading to fail in production.
- Even simple checks, although cheap, rely on JVM class interrogation, and more complex ones may require full reflection.
- The return type in case of success recovers useful
Insulationtype info, but is wrapped so is not directly usable. - It requires considerably more boilerplate (about 45% more than the evidence based one).
- Comes with additional runtime performance costs.
- It's still less ergonomic compared to the compile-time evidence based example. More effort from the devs is required. The API is easy to misuse because neither the compiler nor the IDE can help you.
This should give you a foundational sense of why type‑level evidence is so valuable. And this is only the beginning, Scala’s evidence ecosystem extends far beyond the standard library’s =:= and <:<, encompassing mechanisms for both compile‑time guarantees and refinements, and sometimes even runtime‑assistance.
As mentioned earlier, Scala’s evidence concept mechanisms are not limited to the historical =:= and <:< witnesses that some books and the documentation often highlight. For starters, the standard library itself provide several additional constructs that act as evidence, most of which serve as refinement tools, some purely at compile time, others with limited runtime participation. But only a small subset of these can be used in a blocking capacity, where not providing evidence prevents invalid code from being written.
A few words on how tech books portray evidence: The thing is that many Scala texts do not treat this concept at all.
Of those who do many do not treat it explicitly, neither theoretically nor as a unifying practical idea. Instead, often times, the discussion is brief and limited to the historical forms such as=:=and<:<, as seen for example in the popular Scala for the Impatient by Cay S. Horstmann where chapter 19 (Contextual Abstractions) addresses the concept of evidence... in a way, but subchapter 12 (Evidence) being the most focused section on this topic within the entire chapter.
However, it is worth noting that, by contrast, there is a book called Programming Scala by Dean Wampler that takes a more flexible and thorough approach on this subject. In the chapter Abstracting Over Context: Using Clauses, particularly from the subsection Constraining Allowed Instances up to the end of the chapter, the book illustrates several different ways the idea of evidence can be implemented beyond Scala 3’s canonical style. This makes it one of the few resources that, although not explicitly, approaches evidence as a broader conceptual pattern rather than a single feature.
As for what the future holds, there is one more book that at the time of writing this it has not yet been released, but there are chances that it may approach the topic of evidence similar to how Wampler did it. This book is called Advanced Programming in Scala by Martin Odersky, the creator of Scala. While the published table of contents does not explicitly mention the concept of evidence, it does appear to explore many of the advanced alternative mechanisms for representing this idea.
As we will explore later on, in the broader Scala 3 feature landscape, for these blocking and refining roles it does seem very much to be the case that they can also be fulfilled by inline checks, match‑type reductions, and macro‑generated proofs. Together, these mechanisms support both safe API design and expressive, type‑directed logic.
So, now that we’ve contrasted compile‑time equality evidence with its runtime alternatives in the insulation lamination example, we may very well continue on the Scala standard library path and showcase the other major evidence constructs that reside in there. These tools, whether used to enforce constraints or refine types, they play a central role in the realistic passive-house domain modeling and in any domain where correctness is encoded directly into the type system.
As a heads-up, we will look at:
- ClassTag -> runtime type retention
- Mirror.Of -> structural guarantees for generic meta-programming
- ValueOf -> literal/singleton type evidence
- GADTs and sealed hierarchies -> compiler‑driven type refinement in pattern matching
So, tighten-up your belts as we are going for a ride :)
ClassTag as Refinement
ClassTag can be used to implement a form of refinement evidence that operates with runtime assistance. Unlike purely compile‑time evidence, it bridges a gap created by JVM type erasure, meaning that it preserves the runtime class of a type parameter that would otherwise disappear.
This preserved runtime information allows the compiler to maintain coherence between compile‑time refinements and runtime behavior. When the developer writes a pattern match on an erased type, the compiler rewrites that match into a ClassTag‑based check. The refinement logic expressed in the code remains valid because the runtime now has enough information to verify it.
Let's put it this way, ClassTag enables type‑directed operations that would be impossible under JVM erasure alone. It does not block invalid code at compile time, but, instead, it empowers the developer to write precise logic that the compiler can safely narrow and enforce at runtime. Hence the refinement nature for this evidence.
To see this refinement role in action, consider how ClassTag enables safe retrieval of materials of a particular passive-house certified kind from a MaterialRepository.
package passivhaus.envelope.repository
import scala.reflect.ClassTag
import passivhaus.envelope.materials.*
final case class MaterialRepository(materials: Vector[Material]):
def add(material: Material): MaterialRepository =
copy(materials = materials :+ material)
/*
Only allows retrieving materials of a particular certified type.
*/
def certifiedOnly[A <: PassivhausCertifiedMaterial](
using ClassTag[A]
): Vector[A] =
/*
The ClassTag acts as an enabler: it gives the compiler enough runtime type
information to perform a meaningful type test even after JVM erasure. The
compiler rewrites the pattern match to use this retained runtime class, so
the match is both valid and safe.
Developers coding this kind of evidence are aware that inside the case body the
value is guaranteed to be of type T <: A, so they can write the case body knowingly
*/
materials.collect {
case material: A => material
}
Mirror.Of as Blocker and Refinement
Mirror.Of is a compile‑time evidence mechanism whose primary role is refinement but which also naturally acts as a blocker. It exposes the structural shape of a type to the compiler, allowing it to reason about product and sum types without any runtime reflection. All derivation happens at compile time, and the resulting evidence enables precise, type‑oriented logic inside generic code while also preventing certain methods (through the using clause) from being called on types that lack the required structure.
To see both the refinement and blocking roles in action, consider how Mirror.Of lets us validate insulation specifications generically. By inspecting the compile‑time structure of the type, we can enforce passive‑house domain rules with minimal runtime assistance, only a small amount of reflection is needed when ClassTag participates. The essential logic, however, is driven entirely by compile‑time evidence.
In here, more unit types will make their presence, among them the base unit Ratio and two compound units, KgPerCubicMeter and WattsPerSquareMeterKelvin (which, because of how they’re composed, will in turn require defining a few additional base and compound units).
Since earlier we looked at a simple unit type, this is a good moment to also show how a compound one is structured. As an example, here is the definition of WattsPerSquareMeterKelvin:
/* ... */
object WattsPerSquareMeterKelvin:
opaque type WattsPerSquareMeterKelvin = Double
import Watt.Watt
import SquareMeter.SquareMeter
import Kelvin.Kelvin
@targetName("wsmkApply")
def apply(value: Double): WattsPerSquareMeterKelvin =
require(value > 0, s"U-value must be positive, got $value")
value
@targetName("wsmkFromWattSqmKelvin")
def from(power: Watt, area: SquareMeter, deltaT: Kelvin): WattsPerSquareMeterKelvin =
apply(power.value / (area.value * deltaT.value))
extension (u: WattsPerSquareMeterKelvin)
@targetName("wsmkValue")
private[units] def value: Double = u
@targetName("wsmkWsmkPlus")
def +(other: WattsPerSquareMeterKelvin): WattsPerSquareMeterKelvin = u + other
@targetName("wsmkScalarProduct")
def *(scalar: Double): WattsPerSquareMeterKelvin = u * scalar
@targetName("wsmkWsmkGreaterThan")
def >(other: WattsPerSquareMeterKelvin): Boolean = u > other
@targetName("wsmkWsmkLessThan")
def <(other: WattsPerSquareMeterKelvin): Boolean = u < other
extension (scalar: Double)
@targetName("scalarWsmkProduct")
def *(u: WattsPerSquareMeterKelvin): WattsPerSquareMeterKelvin = u * scalar
And then WindowUValue, the appropriate export object:
/* ... */
object WindowUValue:
export passivhaus.envelope.units.WattsPerSquareMeterKelvin.*
export passivhaus.envelope.units.WattsPerSquareMeterKelvin
Next, inside InsulationSpec let's define an ADT that captures a sealed hierarchy of insulation specs:
package passivhaus.envelope.thermal.specs
import passivhaus.envelope.units.LayerDensity.*
import passivhaus.envelope.units.WindowGValue.*
import passivhaus.envelope.units.WindowUValue.*
import passivhaus.envelope.units.LayerThickness.*
import passivhaus.envelope.materials.Material
enum InsulationSpec:
case ExteriorFacade(
material: Material,
thickness: Meter,
density: KgPerCubicMeter
)
case Window(
uValue: WattsPerSquareMeterKelvin,
gValue: Ratio
)
And now for the slightly more elaborate part 😉. Here are the effects that Mirror.Of, specifically through its Product mirror, has on PassivhausSpecValidator:
package passivhaus.envelope.validators
import passivhaus.envelope.materials.Material
import passivhaus.envelope.materials.PassivhausCertifiedMaterial
import passivhaus.envelope.thermal.specs.InsulationSpec
import passivhaus.envelope.thermal.specs.InsulationSpec.*
import scala.deriving.Mirror
import scala.compiletime.{erasedValue, summonInline}
import scala.reflect.ClassTag
import passivhaus.envelope.units.LayerThickness.*
import passivhaus.envelope.units.LayerDensity.*
import passivhaus.envelope.units.WindowGValue.*
import passivhaus.envelope.units.WindowUValue.*
object PassivhausSpecValidator:
/*
This example happens to have a second layer of evidence which are these field rules.
As you probably figured it out by now this is a blocking type evidence.
The main evidence, which is the catalyst for this second layer, is still the Mirror.
*/
private[envelope] trait PassivhausFieldRule[-T]:
def validate(value: T): Boolean
private[envelope] given PassivhausFieldRule[Meter] with
def validate(c: Meter): Boolean =
c > Meter(0.25)
private[envelope] given PassivhausFieldRule[KgPerCubicMeter] with
def validate(d: KgPerCubicMeter): Boolean =
d > KgPerCubicMeter(15)
private[envelope] given PassivhausFieldRule[WattsPerSquareMeterKelvin] with
def validate(u: WattsPerSquareMeterKelvin): Boolean =
u < WattsPerSquareMeterKelvin(0.85)
private[envelope] given PassivhausFieldRule[Ratio] with
def validate(g: Ratio): Boolean =
g >= Ratio(0.5)
private[envelope] given PassivhausFieldRule[Material] with
def validate(m: Material): Boolean =
m.isInstanceOf[PassivhausCertifiedMaterial]
private[envelope] given PassivhausFieldRule[Any] with
def validate(value: Any): Boolean = false
def validateExteriorFacadeSpec(spec: ExteriorFacade): Boolean = validateInline(spec)
def validateWindowSpec(spec: Window): Boolean = validateInline(spec)
/*
The Mirror.ProductOf[A] parameter is evidence that A is a product type
with compiler-known structure. If A has no mirror, this method cannot
even be called. This is the blocking role of Mirror. It prevents
misuse by rejecting types that do not have structural information.
*/
private inline def validateInline[A <: InsulationSpec](spec: A)(using m: Mirror.ProductOf[A]): Boolean =
/*
Once the mirror exists, the inline match below uses it as refinement
evidence.
The inline match forces the compiler to reduce the match at
compile time. Because m is a Mirror.ProductOf[A], the compiler
knows exactly which case applies for the concrete A at the call
site. This collapses the generic A into a specific domain type.
This is the refinement role of Mirror. It exposes the structure
of A so the compiler can route the logic statically.
*/
inline m match
case _: Mirror.ProductOf[ExteriorFacade] =>
validateExteriorFacade(spec.asInstanceOf[ExteriorFacade])
case _: Mirror.ProductOf[Window] =>
validateWindowInsulation(spec.asInstanceOf[Window])
case _ => validateGeneric(spec)
/*
Specialized paths for known domain shapes. These are selected entirely at compile time via the mirror refinement.
*/
private inline def validateExteriorFacade(spec: ExteriorFacade): Boolean =
validateFields[
(Material, Meter, KgPerCubicMeter)
](Tuple.fromProductTyped(spec))
private inline def validateWindowInsulation(spec: Window): Boolean =
validateFields[
(WattsPerSquareMeterKelvin, Ratio)
](Tuple.fromProductTyped(spec))
/*
Generic fallback, this one uses the mirror to extract the tuple of field types.
*/
private inline def validateGeneric[A <: Product](spec: A)(using m: Mirror.ProductOf[A]): Boolean =
validateFields[m.MirroredElemTypes](Tuple.fromProductTyped(spec))
/*
The recursion is unrolled at compile-time thanks to the inline match, erasedValue and
the specialized literal type tuple resulted from the Mirror refinement
*/
private inline def validateFields[Elems <: Tuple](values: Elems): Boolean =
inline erasedValue[Elems] match
case _: EmptyTuple => true
case _: (h *: t) =>
val fields = values.asInstanceOf[h *: t]
val head = fields.head
val tail = fields.tail
val ok = summonInline[PassivhausFieldRule[h]].validate(head)
ok && validateFields[t](tail)
In the validator, Mirror.ProductOf[A] plays its roles as blocker and refinement very clearly. By requiring a mirror as a contextual parameter, the validator immediately gains a compile‑time gate (if a type has no mirror because it is not a case class, tuple, or any compiler‑generated product then the call is ill‑typed and rejected).
That is the blocking aspect, the mirror serves as structural evidence that must exist before the method is even callable.
Once that evidence is available, the mirror’s refinement power takes over. The inline match on the mirror lets the compiler collapse the abstract A into one of the known domain shapes (ExteriorFacade, Window) or fall back to a generic path. This branching is resolved entirely at compile time, with no runtime reflection. From there, m.MirroredElemTypes exposes the exact field types, enabling the compiler to unroll the tuple and specialize the validation logic for each component.
The PassivhausFieldRule typeclass then builds on what the mirror reveals. For each field type in the tuple, summonInline selects the appropriate rule at compile time. If no rule exists, the code fails to compile, if it does, the rule’s logic is inlined directly into the unrolled recursion. But all of this is downstream of the mirror. As for the inlines, we'll talk more about them in a later chapter.
The mirror is both the admission ticket and the structural description. It allows the type into the system and refines it into a shape the compiler can reason about.
You see, in this way, Mirror.ProductOf is both a gate and a lens. It blocks types that don’t belong, and for those that do, it lets the compiler see deeply enough into their structure to drive precise, domain‑specific validation, and all of it entirely at compile time.
ValueOf as Blocker and Refinement
ValueOf is another promising mechanism for achieving compile‑time evidence. This one links a literal-based singleton type (let's call it just literal type) to its corresponding runtime value. When a type parameter is a literal type, such as "WF" or "MW", the compiler can automatically provide a ValueOf[T] instance that reifies that literal type into an actual value. This allows literal‑driven logic to be expressed without manually passing values around, while not just preserving strong compile‑time guarantees, but also enabling them even more.
Although ValueOf is resolved entirely at compile time, its effects reverberate into runtime. Much like ClassTag, which carries erased type information forward into runtime operations, ValueOf carries the literal value forward into runtime logic. The difference is that ValueOf does not recover erased types, instead, it materializes the value of a literal type. This gives it a dual nature. It is primarily compile‑time evidence, yet it also has a direct and meaningful runtime footprint.
To see how ValueOf supports compile‑time blocking and refinement, consider how literal‑typed material codes can drive passive‑house lookup logic, ensuring that only certified materials can ever be referenced in configuration or thermal‑performance calculations.
But first . . .
Don't worry, it's only one this time ;) and as I mentioned earlier, I won't take up extra space by listing its implementation here.
More precisely, this is where you’ll encounter the compound unit type WPerMeterKelvin and its export object ThermalConductivity.
Ok, now we can design the MaterialLambdaLookup like this:
package passivhaus.envelope.materials.lookup
import scala.compiletime.{erasedValue, constValue, error}
import passivhaus.envelope.materials.PassivhausCertifiedMaterial
import passivhaus.envelope.units.ThermalConductivity.*
/*
MaterialCode is part of the domain’s ubiquitous language.
Encoding the allowed codes as literal types ensures that only
valid codes can ever appear in the system. No runtime validation
is needed, the type system enforces correctness.
*/
type MaterialCode = "WF" | "MW" | "CL"
/*
ValueOf[Code] is evidence that Code is a literal type whose
value is known at compile time. This evidence has two effects:
1. Compile-time blocking: the compiler cannot construct a
MaterialTag unless Code is a literal type. Dynamic strings
or unknown codes simply cannot be used.
2. Runtime reverberation: unlike purely compile-time evidence
(e.g., Mirror), ValueOf reifies the literal type into an
actual runtime value. This allows the literal identity of
the material code to be used in domain objects, logging,
serialization and so on.
*/
final case class MaterialTag[Code <: MaterialCode]()(using val valueOfCode: ValueOf[Code]):
def code: String = valueOfCode.value
/*
This given auto-derives tags using ValueOf evidence.
Basically, the compiler materializes the literal value automatically.
*/
given materialTag[Code <: MaterialCode](using v: ValueOf[Code]): MaterialTag[Code] =
MaterialTag()
/*
ValueOf is used indirectly in here, it is the reason Code is guaranteed
to be a literal type, thus enabling erasedValue-based branching.
*/
object MaterialLambdaLookup:
inline def materialFor[Code <: MaterialCode]: PassivhausCertifiedMaterial =
inline erasedValue[Code] match
case _: "WF" => PassivhausCertifiedMaterial.WoodFiber
case _: "MW" => PassivhausCertifiedMaterial.MineralWool
case _: "CL" => PassivhausCertifiedMaterial.Cellulose
case _ => error("Unhandled material code! Separate implementation is worth considering.")
inline def lambdaFor[Code <: MaterialCode]: WPerMeterKelvin =
inline erasedValue[Code] match
case _: "WF" => WPerMeterKelvin(0.040)
case _: "MW" => WPerMeterKelvin(0.036)
case _: "CL" => WPerMeterKelvin(0.038)
case _ => error("Unhandled material code! Separate implementation is worth considering.")
/*
constValue[Code] retrieves the literal value of Code at compile time.
This is only possible because ValueOf evidence exists for Code.
The comparison `code == constValue[Code]` is reduced statically,
eliminating all runtime branching.
*/
private inline def lambdaTable =
("WF", WPerMeterKelvin(0.040)) *:
("MW", WPerMeterKelvin(0.036)) *:
("CL", WPerMeterKelvin(0.038)) *:
EmptyTuple
private inline def lookupLambda[Code <: MaterialCode](table: Tuple): WPerMeterKelvin =
inline table match
case EmptyTuple =>
error("Invalid material code. It's unreachable due to type constraints.")
case (code: String, value: WPerMeterKelvin) *: tail =>
inline if code == constValue[Code] then value
else lookupLambda<a href="tail">Code</a>
inline def lambdaForViaTable[Code <: MaterialCode]: WPerMeterKelvin =
lookupLambda[Code](lambdaTable)
In the Passivhaus material lookup system, ValueOf opens up room to explore how literal‑based mechanisms might serve as forms of evidence beyond the canonical ones, while in this case playing both roles from the evidence role categorization we’ve been using.
First, it acts as a compile‑time gatekeeper, the blocking role. Any function that requires a ValueOf[Code] can only be called with a literal type argument. If a caller attempts to pass a non‑literal type or a dynamically computed string, the compiler cannot produce the evidence, and the call is rejected. This prevents invalid material codes from ever entering the system and ensures that all lookups are statically verified.
Second, ValueOf acts as a refinement mechanism. Once the compiler has established that a literal type is in scope, the evidence exposes its exact value to inline logic. This enables functions like lambdaFor and materialFor to branch on the literal type using erasedValue or compare it against tuple entries using constValue. Because the literal value is available at compile time, the compiler can reduce these branches statically, eliminating all runtime conditionals. Yet the reified value is still present at runtime, allowing the literal identity of the material code to be used in, for example: logging, tagging, or domain objects such as MaterialTag.
As you can see, having evidence 😉 that ValueOf can act both as a goalkeeper and a midfielder makes it a powerful tool for domains where literal identifiers carry real semantic meaning.
GADTs as Blocking Evidence
GADTs can serve as blocking evidence by encoding domain constraints directly into the type system. Instead of validating combinations at runtime, the type parameter of a GADT acts as evidence that a particular operation is only meaningful for certain variants. When the type parameter does not match, the program becomes ill‑typed, and the compiler blocks the invalid combination before it can even be expressed.
Now, how to apply this in our passive‑house example? We will do it using installation methods that should not be universally applicable. Certain materials can only be installed using specific techniques. By encoding each installation method as a GADT case indexed by the material kind it supports, we ensure that only valid (material, method) combinations are representable. Attempting to pair a material with an incompatible installation method fails at compile time. The GADT’s type parameter becomes the evidence that the method is appropriate for the material, and the absence of matching evidence prevents invalid operations from being written at all.
package passivhaus.envelope.installation
import passivhaus.envelope.materials.PassivhausCertifiedMaterial
/*
Each constructor fixes the type parameter M to the only material that
supports that installation method. This fixed type parameter is a compile‑time proof.
Because the constructor itself carries this proof, the compiler can reject
any attempt to use an installation method with a material whose singleton
type does not match the constructor’s fixed M.
The GADT therefore restricts the space of legal installation methods to the
known cases, and each case encodes its own validity conditions.
*/
enum InstallMethod[M <: PassivhausCertifiedMaterial]:
case Stapled extends InstallMethod[PassivhausCertifiedMaterial.MineralWool.type]
case BlownIn extends InstallMethod[PassivhausCertifiedMaterial.Cellulose.type]
case PressFit extends InstallMethod[PassivhausCertifiedMaterial.WoodFiber.type]
object MaterialInstaller:
/*
The install method requires that the material and the method share the same
type parameter M. Because each GADT constructor fixes M to a specific
material, only valid combinations can satisfy this requirement.
For example:
install(material = Cellulose, withMethod = Stapled) // rejected at compile time
install(material = MineralWool, withMethod = Stapled) // accepted
No runtime checks are needed. The GADT’s type parameter is the evidence,
and the method signature forces the compiler to respect it.
Illegal states are not representable.
*/
def install[M <: PassivhausCertifiedMaterial](
material: M,
withMethod: InstallMethod[M]
): Unit =
println(s"Installing ${material} using $withMethod")
Here, invalid combinations simply cannot be written.
The compiler blocks them before the program can run.
GADTs as Refinement Evidence
When a GADT constructor fixes its type parameter, pattern matching on a value of that GADT automatically narrows the type in each branch.
In the context of a passive‑house insulation layer, this means:
- once you match on a
Layer[M], - the compiler knows exactly which certified material is present,
- and it refines M to that material’s singleton type.
Because LayerData is also parameterized by M, this refinement flows into the data it carries. Inside each branch, the compiler now knows the precise material type stored in data.material, enabling material‑specific operations that would not be legal on the general PassivhausCertifiedMaterial supertype.
This refinement is entirely static.
No runtime type tests, no casting, no isInstanceOf.
The GADT constructor itself is the evidence that drives the narrowing.
For our pilot project, this is especially useful in building‑physics calculations. Each certified material has a known thermal conductivity (λ‑value), and the R‑value of a layer is computed as R = thickness / lambda. Some materials also require material‑specific corrections (compression, moisture expansion, settling), and these adjustments are only available once the type has been refined.
By refining the material type in each match branch, the compiler guarantees that:
- the λ‑value and correction factors correspond to the correct certified material
- all certified materials are handled exhaustively
- no unapproved or unknown material can slip into the calculation
So inside LayerData you can see how all of that looks like in code:
package passivhaus.envelope.layers
import passivhaus.envelope.materials.PassivhausCertifiedMaterial
import passivhaus.envelope.materials.PassivhausCertifiedMaterial.*
import passivhaus.envelope.materials.MaterialCorrections.*
import passivhaus.envelope.units.LayerThickness.*
import passivhaus.envelope.units.ThermalConductivity.*
import passivhaus.envelope.units.ThermalResistance.*
/*
LayerData carries the physical parameters needed for thermal calculations.
It is generic in M so that the material field preserves the refined type.
This is essential: when a Layer[M] is pattern‑matched, the compiler refines M
to a specific singleton type (e.g., MineralWool.type). Because LayerData
stores the material as M, the refined type flows into data.material as well.
This allows material‑specific operations (compressionFactor, settlingFactor,
etc.) to become available only in the branches where the compiler knows the
exact material type.
λ (lambda) is the thermal conductivity of the material.
R‑value = thickness / lambda --- standard building‑physics practice.
*/
final case class LayerData[M <: PassivhausCertifiedMaterial](
material: M,
thickness: Meter,
lambda: WPerMeterKelvin
)
/*
Layer is a GADT whose constructors refine the material type.
Each constructor fixes the type parameter M to the singleton type of the
certified material it represents:
WoolLayer : Layer[MineralWool.type]
FiberLayer : Layer[WoodFiber.type]
CelluloseLayer : Layer[Cellulose.type]
Because LayerData is also parameterized by M, the refined type flows into
the data it carries. Inside each match branch, the compiler knows the exact
material type, enabling material‑specific operations that would otherwise be
illegal on the general PassivhausCertifiedMaterial supertype.
This is compile‑time refinement: no runtime checks, no casting.
The GADT constructors themselves are the refinement evidence.
*/
enum Layer[M <: PassivhausCertifiedMaterial]:
case WoolLayer(data: LayerData[MineralWool.type])
extends Layer[MineralWool.type]
case FiberLayer(data: LayerData[WoodFiber.type])
extends Layer[WoodFiber.type]
case CelluloseLayer(data: LayerData[Cellulose.type])
extends Layer[Cellulose.type]
/*
computeAdjustedRValue demonstrates refinement‑driven specialization.
Pattern matching on Layer[M] refines M to a specific singleton type.
Because LayerData stores its material as M, the refined type flows into
data.material as well.
This enables calling material‑specific correction factors:
• MineralWool.type → compressionFactor
• WoodFiber.type → moistureExpansionFactor
• Cellulose.type → settlingFactor
These extension methods are not available on the general
PassivhausCertifiedMaterial type. They only become legal inside the
corresponding match branch because the GADT has refined M.
This is the essence of GADT refinement: new operations become available
precisely because the compiler now knows the exact material type.
*/
def computeAdjustedRValue[M <: PassivhausCertifiedMaterial](
layer: Layer[M]
): RSquareMeterKelvinPerWatt =
val (layerData, correctionFactor) = layer match
// M is refined to MineralWool.type
case Layer.WoolLayer(data) => (data, data.material.compressionFactor)
// M is refined to WoodFiber.type
case Layer.FiberLayer(data) => (data, data.material.moistureExpansionFactor)
// M is refined to Cellulose.type
case Layer.CelluloseLayer(data) => (data, data.material.settlingFactor)
val adjustedThickness = layerData.thickness * correctionFactor
RSquareMeterKelvinPerWatt.from(adjustedThickness, layerData.lambda)
As for the material corrections themselfs, for the sake of brevity, these values are expressed here as hardcoded literals, even though in a real production scenario they would most likely come from vendor‑supplied material data. Since the goal is to illustrate an alternative evidence mechanism rather than model the full data pipeline, this simplified form it should do for now.
Inside MaterialCorrections you can find how those corrections look like in code:
package passivhaus.envelope.materials
import passivhaus.envelope.materials.PassivhausCertifiedMaterial.*
object MaterialCorrections:
extension (m: MineralWool.type)
def compressionFactor: Double = 0.97 // wool compresses slightly
extension (m: WoodFiber.type)
def moistureExpansionFactor: Double = 1.02 // wood fiber swells a bit
extension (m: Cellulose.type)
def settlingFactor: Double = 0.95 // cellulose settles over time
As you can see, inside each branch, the compiler knows exactly which material type is in play.
No runtime type tests are needed, the refinement is entirely static.
Composed Custom Evidence
Scala’s type system allows developers to express constraints far richer than what the standard library’s built‑in evidence mechanisms can offer on their own. With enums, sealed traits, match types, and recursive typeclasses, we can encode domain‑specific rules directly into the type system itself. Basically, at this point, evidence becomes more than a safety net, it becomes a modeling tool.
Up to this point, our evidence types have mostly answered a simple and very short chain of yes/no questions: "Are these two types equal? Is this type a subtype of that one? Has this GADT branch refined the type parameter?"
These are powerful tools, but they all share one comoomon thing, they are single boolean checks or refinements.
But, many times in production we will find that a more complex and many-factor dependant check-up is required. For example, we may very well want to say "Given this material and this assembly type, run a series of checks and, if everything passes, treat the result as a validated assembly of layers."
This is no longer a simple and tiny chain of yes/no questions. It is a type‑level computation of many factors.
As we have done with the other concepts so far let's implement this in our pilot project.
We begin by defining inside the MoistureCompatible file type‑level functions (type lambdas) that classify both materials and assemblies according to their moisture behavior. MaterialMoistureTolerance assigns a moisture‑tolerance class to each material and AssemblyMoistureRisk assigns a moisture‑risk class to each assembly type. These are then composed into a third type‑level function, MoistureCompatible, that compares the two and yields a Boolean at the type level.
package passivhaus.envelope.assembly.constraints.moisture
import passivhaus.envelope.materials.PassivhausCertifiedMaterial
import passivhaus.envelope.materials.PassivhausCertifiedMaterial.*
import passivhaus.envelope.assembly.AssemblyType
import passivhaus.envelope.assembly.AssemblyType.*
enum MoistureRisk:
case Low
case Medium
case High
import MoistureRisk.*
/*
AssemblyMoistureRisk[A] is a type‑level function that assigns a moisture
risk class to each assembly type.
*/
type AssemblyMoistureRisk[A <: AssemblyType] <: MoistureRisk = A match
case ExteriorWall.type => High.type
case InteriorWall.type => Medium.type
case BelowGradeWall.type => High.type
/*
MaterialMoistureTolerance[M] is a type‑level function that assigns a moisture
tolerance class to each certified material.
*/
type MaterialMoistureTolerance[M <: PassivhausCertifiedMaterial] <: MoistureRisk = M match
case MineralWool.type => High.type
case WoodFiber.type => Medium.type
case Cellulose.type => Low.type
/*
MoistureCompatible[M, A] is a type‑level Boolean that encodes whether
the material’s tolerance is sufficient for the assembly’s moisture risk.
This is a multi-factor type‑level computation:
1. compute MaterialMoistureTolerance[M]
2. compute AssemblyMoistureRisk[A]
3. compare the two and yield true or false
*/
type MoistureCompatible[M <: PassivhausCertifiedMaterial, A <: AssemblyType] <: Boolean =
(MaterialMoistureTolerance[M], AssemblyMoistureRisk[A]) match
case (High.type, High.type) => true
case (High.type, Medium.type) => true
case (High.type, Low.type) => true
case (Medium.type, Medium.type) => true
case (Medium.type, Low.type) => true
case (Low.type, Low.type) => true
case _ => false
Note that this
Booleanvalue isn’t written manually. It’s computed by the compiler from the domain rules encoded in the match types above. In a production system, these rules wouldn’t be hardcoded at the type level, they would likely originate from an external specification service and be parsed at runtime. The compiler cannot consume that runtime data directly, obviosuly, but the encodings type lambdas, match types, and the surrounding ADTs would need to mirror the structure of the richer domain model described by the external spec. In this example, as with others before it, we keep the domain intentionally small and hardcode the rules so we can focus on the mechanics of the type‑level multi-factor computation itself.
Once the type lambda MoistureCompatible[M, A] computes to a Boolean, we need a way to turn that Boolean into evidence the compiler can actually use. That role is played by the evidence type AssemblyMemberValidator[M, A]. Its only instance provider is the validateMaterialAssembly given, which becomes available only if the compiler can prove all the required type‑level checks, in our case is only that MoistureCompatible[M, A] =:= true.
If the type‑level computation yields false, the compiler cannot construct AssemblyMemberValidator[M, A], and the pair (M, A) becomes uninhabited. In other words, no value of that combination can ever exist. This is how invalid (material, assembly) pairs are ruled out at compile time through type‑level computation.
package passivhaus.envelope.validators
import passivhaus.envelope.materials.PassivhausCertifiedMaterial
import passivhaus.envelope.materials.PassivhausCertifiedMaterial.*
import passivhaus.envelope.assembly.AssemblyType
import passivhaus.envelope.assembly.AssemblyType.*
import passivhaus.envelope.assembly.constraints.moisture.MoistureRisk
import passivhaus.envelope.assembly.constraints.moisture.MoistureRisk.*
import passivhaus.envelope.assembly.constraints.moisture.MaterialMoistureTolerance
import passivhaus.envelope.assembly.constraints.moisture.AssemblyMoistureRisk
import passivhaus.envelope.assembly.constraints.moisture.MoistureCompatible
import passivhaus.envelope.layers.Layer
private[envelope] object AssemblyValidator:
/*
AssemblyMemberValidator[M, A] is a custom evidence type.
A value of this type is a proof that the combination of a group member, M, and an
AssemblyType, A, has passed all type‑level checks (for now we have only the moisture
compatibility check, other checks could be added later on as necessary for the domain logic).
The key point: we do not enumerate all (M, A) pairs manually. Instead, we compute whether
a given combination (M, A) is valid using the match types for moisture risk.
*/
private[validators] sealed trait AssemblyMemberValidator[M, A <: AssemblyType]
private[validators] object AssemblyMemberValidator:
/*
This given is only available when MoistureCompatible[M, A] is true.
The constraint is enforced by requiring evidence that
MoistureCompatible[M, A] =:= true.
If the type‑level computation MoistureCompatible[M, A] yields false,
the compiler cannot construct this given, and therefore no
AssemblyMemberValidator[M, A] exists.
*/
given validateMaterialAssembly[M <: PassivhausCertifiedMaterial, A <: AssemblyType](using
moistureCompatibility: MoistureCompatible[M, A] =:= true
): AssemblyMemberValidator[M, A] =
new AssemblyMemberValidator[M, A] {}
This still is evidence in the traditional sense! Why? Because it blocks invalid states and refines what the program knows. But at this stage the evidence is no longer a simple, straight-forward safety check, it’s the outcome of a multi‑step, domain‑specific computation. The type system isn’t merely validating types, it’s enforcing the Passivhaus moisture‑compatibility rules encoded in MaterialMoistureTolerance, AssemblyMoistureRisk, and MoistureCompatible.
Now, an assembly consists of multiple layers, right? So we need evidence for every material in the stack. To achieve that, we introduce a recursive typeclass, AssemblyValidatorOf, as part of the broader AssemblyValidator tools. It walks the tuple one element at a time, ensuring that each layer satisfies the required constraints.
// . . .
private[envelope] object AssemblyValidator:
// . . .
/*
This is a recursive typeclass that walks the tuple of layers and requires
AssemblyMemberValidator[M, A] for each material M of each layer.
Later on, this could also be extended (as it's necessary for the domain logic) to include givens
for different groups, not only layers of materials (for example, it can cover a Tuple of
technologies specific to a particular AssemblyType).
*/
sealed trait AssemblyValidatorOf[Ts <: Tuple, A <: AssemblyType]
object AssemblyValidatorOf:
given emptyAssembly[A <: AssemblyType]: AssemblyValidatorOf[EmptyTuple, A] =
new AssemblyValidatorOf[EmptyTuple, A] {}
given validateLayersAssembly[
M <: PassivhausCertifiedMaterial,
Tail <: Tuple,
A <: AssemblyType
](using
AssemblyMemberValidator[M, A],
AssemblyValidatorOf[Tail, A]
): AssemblyValidatorOf[Layer[M] *: Tail, A] =
new AssemblyValidatorOf[Layer[M] *: Tail, A] {}
The empty tuple is always valid. A non‑empty tuple is valid only if its head layer’s material has an AssemblyValidator for the chosen assembly type, and the tail of the tuple is itself validated by another instance of AssemblyValidatorOf. This recursive structure ensures that every material in the tuple satisfies the moisture‑compatibility rules.
Another recursive typeclass is AllMaterials. This ensures that the tuple contains only layers whose material types are certified Passivhaus materials.
// . . .
/*
This is a recursive typeclass that walks a tuple of layers and ensures that each
element is a Layer[M] where M <: PassivhausCertifiedMaterial.
*/
trait AllMaterials[Ts <: Tuple]
object AllMaterials:
given emptyMaterialLayersTuple: AllMaterials[EmptyTuple] =
new AllMaterials[EmptyTuple] {}
given validateLayersOfPCM[
M <: PassivhausCertifiedMaterial,
Tail <: Tuple
](using
AllMaterials[Tail]
): AllMaterials[Layer[M] *: Tail] =
new AllMaterials[Layer[M] *: Tail] {}
Together, AllMaterials and AssemblyValidatorOf guarantee that the layer stack is both structurally well‑formed and moisture‑compatible.
And now, when it comes to the actual construction of a moisture-compatible layer assembly we will define two ways through which to do it:
- directly through the inner factory
AssemblyFactory - or through the factory method
LayersOfMaterialsAssembly.makewhich eventually passes the control to the inner factory. This method is more for aiding type inference of the two type params the factory requires, thus making the call site for the creation of the assembly a bit more cleaner.
package passivhaus.envelope.assembly.layers
// . . .
/*
This LayersOfMaterials type lambda maps a tuple of material types Ms into a tuple of
Layer[M & PassivhausCertifiedMaterial] types (a type intersection which,
in this case, in practice resumes to Layer[M] types).
It is used internally to store the layers inside the LayersOfMaterialsAssembly case class.
*/
private[assembly] type LayersOfMaterials[Ms <: Tuple] =
Tuple.Map[Ms, [M] =>> Layer[M & PassivhausCertifiedMaterial]]
final case class LayersOfMaterialsAssembly[Ms <: Tuple] private (
layers: LayersOfMaterials[Ms]
):
/*
As you already saw with the Layer class, here too, in LayersOfMaterialsAssembly,
we define a method of calculating the adjusted R value, only that this time
it's the collective R values
*/
def totalAdjustedRValue: RSquareMeterKelvinPerWatt =
layers
.toList
.asInstanceOf[List[Layer[PassivhausCertifiedMaterial]]]
.map(computeAdjustedRValue)
.reduce(_ + _)
object LayersOfMaterialsAssembly:
/*
Mainly used for type param inference aid.
*/
def make[A <: AssemblyType]: AssemblyFactory[A] =
new AssemblyFactory[A]
/*
The apply method is enabling the multi-factor evidence. Mainly two
type-level computations.
Both of wich are recursive typeclasses that walk the tuple of layers
and ensure that all required evidence exists.
*/
class AssemblyFactory[A <: AssemblyType]:
def apply[Ts <: Tuple](layers: Ts)(using
AllMaterials[Ts],
AssemblyValidatorOf[Ts, A]
): LayersOfMaterialsAssembly[Ts] =
LayersOfMaterialsAssembly(layers.asInstanceOf[LayersOfMaterials[Ts]])
Either way the compiler must satisfy both AllMaterials and AssemblyValidatorOf. This means the compiler must:
- Infer the tuple of materials from the provided layers.
- Confirm that each element of the tuple is a valid
Layer[M]for some certified material M. - Compute
MaterialMoistureTolerancefor each material in the tuple. - Compute
AssemblyMoistureRiskfor the chosen assembly type. - Evaluate
MoistureCompatiblefor each material–assembly pair. - Construct
AssemblyMemberValidatorfor each material where compatibility holds. - Recursively assemble these into
AssemblyValidatorOffor the entire tuple.
If any of these steps fail, if even one material is incompatible with the assembly type, the compiler cannot construct the required evidence, and the assembly cannot be expressed in the program.
This is a compile‑time guarantee that the assembly respects the Passivhaus moisture‑compatibility rules. In this case we only have one compatibility rule, but many others can be added like sound absorption, load-bearing capacity, and so on.
Basically, the type system becomes an active participant in enforcing building‑physics constraints.
Alright, look. This could be a bit mentally draining, but since you’ve made it this far, for sure you're not someone that gives up easily.
So... let's recap what we showcased in this chapter :)
At this point, type‑evidence‑driven design has fully crossed into domain modeling. We are no longer using the type system merely to avoid mistakes or catch trivial errors. Instead, we are using it to encode the logic of the domain itself.
The combination of MaterialMoistureTolerance, AssemblyMoistureRisk, MoistureCompatible, AssemblyMemberValidator, AssemblyValidatorOf, and AllMaterials forms a type‑level rule engine. The compiler evaluates these rules every time an assembly is constructed. The result is a system where invalid states are not just discouraged, they are impossible to represent (yes, I know I’ve said this a few times already, but come on, it’s such a gloriously Thanos‑level move. We basically, during the development stage, just snapped them out of existence 🙃).
This is the essence of type‑evidence‑driven design! The program becomes a faithful reflection of the domain, and the compiler becomes a validator of domain rules. The developer is guided toward correct constructions not by documentation or runtime checks, but by the structure of the type system itself.
Now, it’s worth noting that there are several ways to express the composition logic behind typeclass evidence. These other approaches typically involve inline definitions, summon based methods, and, when the most amount of liberty and power is needed, devs could make use of macros.
So far, we’ve looked at Scala 3’s approach to evidence within the context of an application-level project. In the following chapters, we’ll examine these mechanisms through two real‑world library projects that make heavy use of them. More precisely through Shapeless 3 and Tapir. As they provide excellent, practical examples of how inline matching and summon-based derivation come together to build sophisticated typeclass derivation systems. And also, in the context of macro-based composition, we will take a glimpse in the ZIO library ecosystem as well.
Designing Compound Custom Evidence Using Inlines and Summons
In the previous chapter we noted that Scala offers several ways to express the composition logic behind typeclass evidence. Now, the inline definitions, summon‑based methods, and, when the most freedom is needed, macros, all of these provide complementary mechanisms for building compound custom evidence.
Previously we designed evidence on an application-level, in this chapter, we will briefly experience the library-level design with inlines and summons, more precisely we turn to two real‑world libraries that rely heavily on these other approaches. The particular areas we'll examine are Shapeless‑3's kinds derivation and Tapir's Iron integration. They offer concrete, production‑tested examples of how inline matching and summon‑based derivation can be used to assemble sophisticated evidence structures.
Before starting to get the ball rolling, it helps to clarify two ideas that will appear repeatedly:
- Calling summon methods, like
summonInlineit's still considered as applying evidence! It is not that different from ausingclause. The only difference is that you can request the evidence inside a method body, inside a branch, or inside a recursive function. This gives you more control over when and how evidence is pulled into scope.- An inline given is a given whose body is expanded at compile time. This allows the compiler to inspect the structure of types, pattern‑match on them, and choose derivation paths dynamically.
Inline‑driven Compound Evidence in Shapeless‑3
Let's start with a concise definition. Shapeless‑3 is a generic programming library that provides automatic derivation of typeclass instances.
Good! Now, for this example, we'll take a look inside the kinds.scala file, which contains several pieces of code that illustrate how the library uses inline derivation to assemble compound evidence. The goal here is not to describe the entire file, but to highlight a few representative snippets where this pattern becomes visible.
One such piece is a recursive match type:
/** Applies `F` to all elements of the tuple type `T`. Similar to [[Tuple.Map]] but generalized to this kind. */
type LiftP[F[_ <: Up], T <: Tup] <: Tuple = Mono[T] match
case _ *: _ => F[Head[T]] *: LiftP[F, Tail[T]]
case _ => EmptyTuple
LiftP does not produce evidence by itself. Instead, it describes the shape of the evidence that later definitions will construct: one F[...] for each component of a tuple.
It is a type‑level helper that participates in the composition process.
Elsewhere in the file, two inline givens make use of this helper:
/** Given a [[scala.deriving.Mirror.Product]], provides instances of the type class `F` for all fields of `T`. */
inline given mkProductInstances[F[_ <: Up], T <: Up](using gen: Mirror.Product of T): ProductInstances[F, T] =
ErasedProductInstances[self.type, F[T], LiftP[F, gen.MirroredElemTypes]](gen)
/** Given a [[scala.deriving.Mirror.Sum]], provides instances of the type class `F` for all variants of `T`. */
inline given mkCoproductInstances[F[_ <: Up], T <: Up](using gen: Mirror.Sum of T): CoproductInstances[F, T] =
ErasedCoproductInstances[self.type, F[T], LiftP[F, gen.MirroredElemTypes]](gen)
These given definitions illustrate how Shapeless turns the type‑level structure described by LiftP into value‑level evidence. Each receives a structural mirror (Mirror.Product or Mirror.Sum), computes the tuple of evidence types via LiftP, and wraps the result into a domain‑specific structure. If any component instance is missing, the blocking hopes in and so the derivation fails.
A third piece of code shows how Shapeless selects between these two definitions:
/** Given a [[scala.deriving.Mirror]], provides instances of the type class `F` for all fields or variants of `T`. */
inline given mkInstances[F[_ <: Up], T <: Up](using gen: Mirror of T): Instances[F, T] = inline gen match
case given (Mirror.Product of T) => mkProductInstances[F, T]
case given (Mirror.Sum of T) => mkCoproductInstances[F, T]
This inline given acts as a dispatcher. It inspects the structure of T through its mirror and chooses the appropriate constructor.
The composition logic is quite visible in here. The structure of the type determines which evidence is assembled.
And finally, the file also exposes the appliance of the mkInstances evidence provider:
/** Summon instances of the type class `F` for all fields or variants of the type `T`. */
def Instances[F[_ <: Up], T <: Up](using inst: Instances[F, T]): inst.type = inst
Requesting Instances[F, T] triggers the chain of inline givens. The compiler resolves the using clause by expanding mkInstances, which delegates to the appropriate branch and ultimately constructs the composite evidence described by LiftP.
Again, these snippets do not represent the entire purpose of the file, but they offer a clear view of how Shapeless uses inline matching and type‑level helpers to assemble compound evidence.
Summon‑driven Compound Evidence in Tapir-Iron
Tapir's Iron integrtion uses refinement types into Tapir’s schema and validation system. The file TapirCodecIron.scala contains several places where summon‑based derivation is used to build compound evidence.
Again, the goal here is not to describe the entire file, but to observe a few representative examples.
One such example is a recursive function, summonValidators, that gathers per‑predicate validators:
private inline def summonValidators[N, A <: Tuple]: List[ValidatorForPredicate[N, Any]] = {
inline erasedValue[A] match
case _: EmptyTuple => Nil
case _: (head *: tail) =>
val headValidator: ValidatorForPredicate[N, ?] = summonFrom {
case pv: PrimitiveValidatorForPredicate[N, `head`] => pv
case _ => summonInline[ValidatorForPredicate[N, head]]
}
headValidator.asInstanceOf[ValidatorForPredicate[N, Any]] :: summonValidators[N, tail]
}
This function inspects the tuple of predicates A. For each head, it attempts to obtain a primitive validator, if none is available, it falls back to summonInline[ValidatorForPredicate[N, head]].
Each call to summonInline is an application of evidence.
Eventually, the recursion accumulates a list of validators, one for each predicate.
In another snippet, the given validatorForAnd is presented. Here it is shown how these validators are combined when the predicate is an intersection:
inline given validatorForAnd[N, Predicates](using mirror: IntersectionTypeMirror[Predicates]): ValidatorForPredicate[N, Predicates] =
new ValidatorForPredicate[N, Predicates] {
val intersectionConstraint = new Constraint.IntersectionConstraint[N, Predicates]
val validatorsForPredicates: List[ValidatorForPredicate[N, Any]] = summonValidators[N, mirror.ElementTypes]
override def validator: Validator[N] = Validator.all(validatorsForPredicates.map(_.validator): _*)
override def makeErrors(value: N, errorMessage: String): List[ValidationError[?]] =
if (!intersectionConstraint.test(value))
List(
ValidationError[N](
Validator.Custom(_ =>
ValidationResult.Invalid(intersectionConstraint.message) // at this point the validator is already failed anyway
),
value
)
)
else Nil
}
This inline given applies only when Predicates is an intersection type, enforced by IntersectionTypeMirror. It extracts the component predicates, invokes summonValidators to obtain evidence for each, and then combines the resulting validators into a single composite validator. If any component validator is missing, the derivation is blocked.
A usage site appears in the schema derivation:
given ironTypeSchema[Value, Predicate](using
vSchema: Schema[Value],
constraint: RuntimeConstraint[Value, Predicate],
validatorTranslation: ValidatorForPredicate[Value, Predicate]
): Schema[Value :| Predicate] =
vSchema.validate(validatorTranslation.validator).map[Value :| Predicate](v => v.refineOption[Predicate])(identity)
Here, validatorTranslation may be the composite validator produced by validatorForAnd. The given combines the base schema, the runtime constraint, and the validator into a schema for the refined type. This is where the compound evidence is consumed.
These snippets illustrate how Tapir's Iron integration uses summon‑based recursion and inline givens to assemble evidence from multiple components.
A Few Words on Macro-Driven Evidence
Alright, this article is already getting pleasantly dense, and macros are one of those topics that could easily swallow an entire lecture on their own. So I don't plan to keep you here that much longer. Think of this section as a small and friendly detour, just enough to spark your curiosity, give you a sense of the landscape, and maybe tempt you into exploring macros more deeply on your own.
Macros occupy a special place in Scala’s compile‑time ecosystem. Inline givens and summon‑based derivation operate within the, should I say, normal reduction rules of the type system. They could be used to match on types, recurse over tuples, and assemble evidence step by step. Macros, by contrast, along with Quotes and Splices, let a library, or even an application, participate in compilation in a more open‑ended way. They can inspect the full structure of a type, generate code, and construct evidence programmatically. In the context of evidence, as you would expect, macros can play the role of the blocker but they could also take on a refinement‑like role. They can analyze a type or even a value at compile time and produce evidence that reflects a more precise understanding of it.
This makes macros particularly attractive when the shape of the evidence depends on information that is awkward to express through match types alone, or when the derivation logic needs to be more flexible than what inline pattern matching comfortably allows. Many libraries use them sparingly, precisely because they offer so much freedom. They can synthesize complex structures, tailor error messages to the exact shape of a type, and encode domain rules that go beyond what the other techniques in this chapter can conveniently capture.
And here’s the sweet part. From a developer’s perspective (the one who uses these macros, not the one that implements them), macro‑driven derivation often feels indistinguishable from canonical typeclass evidence.
This brief mention is not meant to teach macros, only to gesture toward them. If inline matching and summon‑driven derivation now feel familiar, macros are the natural next frontier.
Trust me, they will reward your deeper study!
And they open the door to some of the most expressive patterns in Scala’s compile‑time world.
Inline and summon‑based derivation already allow for sophisticated composition (like structure inspection, branching, recursion, and assembly of complex proof objects), but macros extend this further. A macro can inspect the full structure of a type, run arbitrary compile‑time logic, generate new types or instances, and decide whether to succeed or fail with custom error messages. In effect, a macro acts as a programmable compile‑time proof engine.
Ok, enough rhetoric, let's look at a practical example. 🚀
A perfect showcase for this is ZIO Schema.
So, to reiterate, the experience of Scala evidence (meaning the way it feels to the user dev) can also be expressed through other features different from typeclasses. Macros, with quotes and splices, being the most powerful of these!
In order to ilustrate that through a real-world usage, lets take a look to a portion of the DeriveSchema.scala file of ZIO Schema.
From the outside, the API is very simple:
extension (s: Schema.type) transparent inline def derived[A] = DeriveSchema.gen[A]
object DeriveSchema {
transparent inline def gen[T]: Schema[T] = ${ deriveSchema[T] }
private def deriveSchema[T: Type](using Quotes): Expr[Schema[T]] =
DeriveSchema().deriveSchema[T](top = true)
}
In here you can see the macro entry point, the gen[T] method. It delegates the work to the macro implementation, deriveSchema[T: Type], which in turn invokes the deriveSchema[T: Type] method defined on the DeriveSchema instance. That final method is the one that actually performs the derivation logic, as you’ll see shortly.
Anyways, a user dev could then write val userSchema: Schema[User] = Schema.derived[User] and expects one of two outcomes:
a
Schema[User]is produced, orcompilation fails with a clear message explaining why
Usercannot be derived.
That is exactly the same interaction pattern as val showUser: Show[User] = summon[Show[User]]
The internal mechanics are different, but the contract with the developer is the same.
Inside DeriveSchema, the macro performs a kind of compile‑time refinement over the type:
A few things stand out here:
The macro first checks for recursion via the
Stackand usesSchema.deferwhen it finds a previously seen type.It then tries to reuse existing evidence with
Expr.summon[Schema[T]]when not at the top level.It pattern‑matches on the shape of the type (
List,Either,Option, collections,Chunk, mirrors for products and sums, sealed traits,OrTypeunions).And when none of the supported shapes match, it calls
report.errorAndAbortwith a descriptive message.
From the user’s point of view, this is indistinguishable from typeclass evidence. With typeclasses, summon[Show[A]] either finds an instance or fails. In a similar way, with ZIO Schema, Schema.derived[A] either produces a Schema[A] or fails.
These blocking modes are analogous. Unsupported types lead to compile‑time errors, and both mechanisms act as compile‑time guards that enforce constraints on which types are acceptable.
So, as you have seen in the exemple of ZIO Schema, while macros are not evidence in the canonical Scala sense (they don’t participate in implicit resolution), they fulfil the same practical role. They are invoked in the same just give me the instance style, they succeed or fail in the same way, and they enforce the same kind of type‑level guarantees. The key difference is internal. Typeclasses look up pre‑defined instances, whereas macros generate the result on the fly. But the thing is, for most user-devs, that distinction is invisible.
Conclusion
Now that we’ve come to the end, we should ask ourselves: Why does all of this matter, and what is the practical impact on code and teams?
Well, all of this type‑level machinery for evidence has a real effect on how Scala developers write software!
APIs become harder to misuse.
Domain invariants become impossible to violate.
Refactoring becomes safer and more predictable.
Complex logic becomes simpler because invalid states are unrepresentable.
Teams gain confidence that the compiler is enforcing the rules they care about.
And with less boilerplate, the codebase becomes lighter and more expressive.
But there is a deeper point running through everything we’ve explored.
Scala’s canonical story for evidence is typeclasses, that’s the familiar shape. Yet the experience of evidence can be expressed through other Scala 3 features as well: inline definitions, summon‑driven derivation, enrichment of evidence logic through typelevel computations (match types, type lambdas and whatnot) and, at the far end of the spectrum, the freedom king of compile-time logic expression, macros with quotes and splices. These mechanisms differ internally, but from the developer’s perspective they often feel the same.
You ask the compiler for something, and it either gives you the result, refines it or tells you why it shall not pass.
This flexibility matters. It means that evidence is not tied to a single construct, but is instead a design space, a way of modeling domain rules, shaping APIs, and guiding developers toward correct usage. Whether the evidence is looked up, computed, or generated, the effect on the domain model is the same, the compiler becomes an active participant in enforcing the logic of the system.
You see, type‑level evidence isn’t just an academic curiosity for geeks with too much time on their hands. Well, it is all that :) but more importantly, it's also a practical force that shapes codebases, workflows, and engineering culture. And Scala 3 gives us more than one way to express it.
It was quite an adventure, alright! But, like all good things, it eventually had to come to an end...
Remember tho, every ending is just a new beggining to chase other awesome experiences! 😉
So, thank you for taking the time to explore how evidence works in Scala, the different ways we can express the same underlying idea, and how these choices shape everyday development practice. And last but not least, thank you for your interest in software engineering!
References
- https://docs.scala-lang.org/scala3/guides/
- https://docs.scala-lang.org/scala3/reference/
- https://docs.scala-lang.org/tour/
- https://medium.com/@markgrechanik/type-refinements-in-scala-making-your-types-more-sophisticated-than-your-friends-23600b2305d2
- https://github.com/scala/scala3/
- https://github.com/BuffBorg-Lectures/rethinking-evidence-passivhaus
- https://docs.scala-lang.org/scala3/book/
- https://horstmann.com/scala/
- https://www.oreilly.com/library/view/programming-scala-3rd/9781492077886/
- https://www.manning.com/books/functional-programming-in-scala-second-edition
- https://www.artima.com/shop/advanced_programming_in_scala_5ed
- https://www.artima.com/shop/programming_in_scala_5ed
- https://nightly.scala-lang.org/docs/internals/gadts.html
- https://docs.scala-lang.org/sips/
- https://github.com/typelevel/shapeless-3
- https://github.com/softwaremill/tapir
- https://github.com/zio
- https://zionomicon.com/










Top comments (0)