Discuss the role of 'implicitly' in Scala.
Instruction: Explain how the implicitly method retrieves contextual values and provide an example, noting the Scala 3 summon alternative.
Updated
implicitly[A] is a method in Predef, not a keyword. It requests a contextual value of type A and returns the value selected by compile-time implicit resolution. Scala 3 commonly uses summon[A] for this purpose.
final case class Person(age: Int)
object Person {
given Ordering[Person] = Ordering.by(_.age)
}
def older(left: Person, right: Person)
(using Ordering[Person]): Person =
implicitly[Ordering[Person]].max(left, right)
@main def evidenceExample(): Unit = {
val young = Person(20)
val old = Person(40)
assert(older(young, old) == old)
assert(summon[Ordering[Person]].compare(young, old) < 0)
assert(older(young, old)(using Ordering.by[Person, Int](-_.age))
== young)
}
The companion's ordering is available through implicit scope. The method uses its contextual parameter, so an explicitly supplied alternative changes its behavior. The name older assumes age-increasing ordering; the reversed call illustrates why the instance's semantics matter, not just its type.
Resolution requires an eligible instance. A missing instance or unresolved ambiguity is a compile error. This is not runtime discovery of a global service registry, and the method does not prove that a user-defined ordering satisfies ordering laws. Predef implementation Contextual resolution
Related Questions
-
medium
-
hard
-
hard
-
hard