Of course! Let's break down type evidence in Scala 3. It's a powerful concept that, once understood, unlocks a lot of the magic behind Scala's type system.
The Core Idea: What is Type Evidence?
At its heart, type evidence is a "proof" that the compiler can use to verify a relationship between types.
Think of it like this: Imagine you have a function that can only accept a European passport.
def enterEurope(passport: EuropeanPassport): Unit = { ... }
This is easy. But what if you have a function that accepts any passport, but inside the function, you need to do something only a European passport allows? You need some way to prove that the passport you're holding is European.
This "proof" is type evidence. In Scala, this proof isn't a piece of paper; it's a special value that the compiler automatically provides at compile time. If the compiler can't find or create this value, you get a compile-time error, preventing you from writing unsafe code.
How it Works in Scala 3: given and using
In Scala 3, type evidence is requested using a using clause and provided by a given instance. This is the modern replacement for Scala 2's implicit.
using: "I need proof of X." (This is the function requesting evidence).
given: "Here is the proof of X." (This is the compiler or your code providing the evidence).
// A function that requests evidence
def myFunction[A, B](/*... normal parameters ...*/)(using evidence: SomeProof[A, B]): ReturnType = {
// Because this function compiles, we are GUARANTEED that the proof is valid.
}
// The compiler finds or you define a 'given' instance that can be used as proof.
given myProof: SomeProof[String, Int] with { ... }
Now, let's look at the most common types of "proof" (evidence) you'll encounter.
1. Subtype Evidence: <:<
This is the most common form of evidence. It proves that one type is a subtype of another. The evidence type is A <:< B, which reads as "A is a subtype of B".
Use Case: You want to write a generic function, but enforce that the generic type T must be, for example, a Seq.
Let's write a function that takes a collection of something and processes it only if that something is a sequence of numbers.
def sumOfFirstThree[T](collection: T)(using ev: T <:< Seq[Int]): Int = {
// Because of the 'using' clause, the compiler GUARANTEES that 'collection'
// is a subtype of Seq[Int]. We can safely call Seq methods on it.
// The 'ev' is the proof object, but we often don't need to use it directly.
collection.take(3).sum
}
// --- How it's used ---
// ✅ This works
val list = List(10, 20, 30, 40)
val result = sumOfFirstThree(list) // Compiles!
// Why? The compiler sees T is List[Int].
// It knows List[Int] is a subtype of Seq[Int].
// So it automatically provides a 'given' instance of type 'List[Int] <:< Seq[Int]'.
println(result) // Output: 60
// ❌ This fails at compile time
val set = Set(1, 2, 3)
// sumOfFirstThree(set) // COMPILE ERROR!
// The error message is very helpful:
// Cannot prove that Set[Int] <:< Seq[Int].
// The compiler tried to find a 'given' instance for the proof, but failed.
This is much safer than casting with isInstanceOf/asInstanceOf, which would fail at runtime.
2. Type Equality Evidence: =:=
This evidence proves that two types are exactly the same. The evidence type is A =:= B, which reads as "A is the same type as B".
Use Case: Imagine a generic function that replaces an item in a list. You want to ensure the new item has the exact same type as the items already in the list.
def safeReplace[Container, Item](
xs: List[Container],
newItem: Item
)(using ev: Container =:= Item): List[Container] = {
// Because of the 'using' clause, we know Item is the same type as Container.
// So it's safe to create a new List[Container] with newItem.
xs.tail :+ newItem
}
// --- How it's used ---
// ✅ This works
val numbers = List(1, 2, 3)
val newNumbers = safeReplace(numbers, 100) // Compiles!
// Why? The compiler sees Container is Int and Item is Int.
// It can easily provide a 'given' instance of 'Int =:= Int'.
println(newNumbers) // Output: List(2, 3, 100)
// ❌ This fails at compile time
val strings = List("a", "b", "c")
// safeReplace(strings, 123) // COMPILE ERROR!
// Error: Cannot prove that String =:= Int.
// The compiler correctly prevents you from adding an Int to a List[String].
3. Multiversal Equality Evidence: CanEqual
This is a new and extremely important form of type evidence in Scala 3, designed to make the equality operator (==) safer.
The Problem in Scala 2: In Scala 2, you could compare almost anything, which often hid bugs.
List(1, 2, 3) == "hello" // Compiles in Scala 2, returns `false` at runtime. This is likely a typo/bug.
The Scala 3 Solution: In Scala 3, the == operator requires type evidence in the form of a given CanEqual[L, R] instance. This evidence proves that it's "sensible" to compare type L with type R.
// In Scala 3's standard library (simplified):
trait CanEqual[L, R]
extension [L](lhs: L)
def == (rhs: Any): Boolean = ... // Simplified
def != (rhs: Any): Boolean = ... // Simplified
When you write a == b, the compiler looks for a given CanEqual[TypeOfA, TypeOfB].
How it Works in Practice:
- Scala provides
given instances for sensible comparisons (e.g., CanEqual[Int, Int], CanEqual[T, T]).
- It also provides them for comparing collections of the same type, e.g.,
List[Int] and Vector[Int].
- Crucially, there is no
given instance for CanEqual[List[Int], String].
import scala.language.strictEquality // Often enabled to make the rule stricter
// ✅ This works
1 == 1 // The compiler finds a 'given CanEqual[Int, Int]'
List(1, 2) == Vector(1, 2) // The compiler finds a 'given CanEqual[List[Int], Vector[Int]]'
// ❌ This now fails at compile time!
// List(1, 2) == "hello" // COMPILE ERROR!
// Error: Cannot prove that List[Int] CanEqual String
This use of type evidence catches potential bugs at compile time instead of letting them become silent runtime failures.
Summary: Scala 2 vs. Scala 3
| Feature | Scala 2 (implicit) | Scala 3 (given/using) |
|---|
| Requesting Evidence | An implicit parameter list: (implicit ev: A <:< B) | A using clause: (using ev: A <:< B) |
| Providing Evidence | implicit val or implicit def | given instance: given CanEqual[Int, Int] = CanEqual.derived |
| Clarity | implicit was overloaded for many purposes (conversions, extension methods, parameters). | using is solely for term inference (contextual parameters). It's more explicit and less "magical". |
| New Concepts | CanEqual did not exist. | CanEqual is a prime example of using type evidence for enhanced safety. |
In conclusion, Type Evidence is a core mechanism that allows the Scala compiler to enforce complex type-level constraints. By requesting "proof" via a using clause, you can write generic code that is both flexible and extremely safe, as the compiler validates your assumptions before the program even runs.