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.*Source:https://dev.to/ionra/rethinking-evidence-in-scala-3-concepts-mechanisms-and-real-world-engineering-impact-10m4Related posts

How AI Is Changing the Way Companies Hire, Manage and Measure Performance
Zero-Dependency Verified Agents: Cited or Refused, Gated in CI

Measure barge-in stop time from a stereo call recording in Python
I listed a pay-per-call API on Lightning Faucet's L402 gateway — here's what actually happens




