Explain the role of implicits in Scala's type evidence.
Instruction: Discuss how implicits are used in Scala to provide type evidence and the implications for type safety.
Updated
A contextual parameter can require evidence of a type relationship or a capability. The compiler resolves a suitable value and passes it as an ordinary argument. In Scala 3, using and given express this directly; Scala 2 uses implicit parameters and instances.
def asStrings[A](values: List[A])(using ev: A =:= String): List[String] =
values.map(ev.apply)
trait Label[A] { def apply(value: A): String }
given Label[Int] with {
def apply(value: Int): String = s"number:$value"
}
def label[A](value: A)(using instance: Label[A]): String = instance(value)
@main def evidenceExample(): Unit = {
assert(asStrings(List("a", "b")) == List("a", "b"))
assert(label(7) == "number:7")
}
A =:= String witnesses type equality and supplies a safe conversion within the ordinary typed program. Calling asStrings on List[Int] cannot obtain that equality evidence. <:< can express a subtype relationship instead. Equality evidence
Label[A] makes a different promise: an implementation with the required interface exists. The compiler does not prove that it returns truthful text, never throws, obeys algebraic laws or correctly encodes a format. Likewise, finding a JsonSerializer[A] does not prove that its output is valid JSON. Validate implementations and runtime input separately.
Implicit conversions are not required for this pattern and can make dependencies less visible. Keep instances scoped predictably, use explicit using arguments to choose a policy when needed, and investigate missing or ambiguous searches with a small summon[RequiredType] example. Evidence is not an authorization boundary and can be undermined by deliberate unsafe casts, fabricated values or nulls.