In Scala 3, type evidence (often called implicit evidence in Scala 2) uses contextual abstractions (given/using) to prove relationships between types at compile time. Here's a breakdown with key concepts and examples:
1. Built-in Type Evidence
Scala provides predefined evidence types for common constraints:
A =:= B: Proves A is exactly type B.
A <:< B: Proves A is a subtype of B.
scala
def processExact[A, B](a: A)(using ev: A =:= B): B =
ev(a) // Convert A to B safely
def processSubtype[A, B](a: A)(using ev: A <:< B): B =
ev(a) // Treat A as B
Usage:
scala
val exact: String = processExact[String, String]("Hello") // Compiles
val sub: Any = processSubtype[String, Any]("Hi") // Compiles (String <:< Any)
// processExact[Int, String](123) // Fails: Int ≠ String
2. Custom Type Evidence
Define evidence for custom constraints:
scala
// Define evidence type
trait IsNumeric[A]:
def describe: String
// Provide evidence for Int/Double
given IsNumeric[Int] with
def describe: String = "Integer"
given IsNumeric[Double] with
def describe: String = "Double"
// Constrain function using evidence
def analyze[T](value: T)(using ev: IsNumeric[T]): String =
s"$value is ${ev.describe}"
Usage:
scala
analyze(42) // "42 is Integer"
analyze(3.14) // "3.14 is Double"
// analyze("text") // Fails: No IsNumeric[String]
3. Context Bounds (Syntax Sugar)
Simplify evidence syntax with context bounds T: Evidence:
scala
// Equivalent to: [A](using IsNumeric[A])
def analyze[A: IsNumeric](value: A): String =
val ev = summon[IsNumeric[A]] // Retrieve evidence
s"$value is ${ev.describe}"
4. Advanced: Deriving Evidence
Automatically generate evidence using derives:
scala
// Define a type class
trait JsonSerializer[A]:
def serialize(a: A): String
// Auto-generate evidence for case classes
case class Person(name: String) derives JsonSerializer
// Generated instance:
// given JsonSerializer[Person] = ...
Key Changes in Scala 3 vs. Scala 2
Feature
Scala 2
Scala 3
Evidence Syntax
implicit ev: T
using ev: T
Evidence Retrieval
implicitly[T]
summon[T]
Context Bounds
[T: Evidence]
Same (but given instances)
Implicit Conversions
Enabled by default
Requires explicit scala.Conversion
When to Use Type Evidence
Enforce type constraints (e.g., A must be a subtype of B).
Conditional implementations (e.g., different logic for different types).
def safeCast[A, B](a: A)(using ev: A <:< Option[B]): Option[B] =
a // Works because A is proven to be Option[B]
safeCast(Some(42)) // Some(42)
// safeCast("oops") // Fails: String ≠ Option[?]
Type evidence ensures compile-time safety by leveraging Scala's type system to validate constraints before runtime.