Given Scopes
Given scopes are the places the compiler searches when it needs a given value. Two such places are the current scope and the companion object of a type.
A companion given needs no import
The companion object of Book holds a Describer for Book. Summon finds it with no import in the program.
trait Describer[T]:
def describe(x: T): String
case class Book(title: String, pages: Int)
object Book:
given Describer[Book] with
def describe(b: Book): String = b.title + ":" + b.pages.toString
@main def main(): Unit =
println(summon[Describer[Book]].describe(Book("Scala", 120)))A given in the same file is already in scope
A given written at the top level of the file is in the current scope. Summon finds it with no import.
given Int = 9
@main def main(): Unit =
println(summon[Int] + 1)A helper call also finds the companion given
The show helper takes its Describer as a using parameter. The call leaves it out, so the compiler fills it from the companion object of Book.
trait Describer[T]:
def describe(x: T): String
case class Book(title: String, pages: Int)
object Book:
given Describer[Book] with
def describe(b: Book): String = b.title + ":" + b.pages.toString
def show[T](x: T)(using d: Describer[T]): String = d.describe(x)
@main def main(): Unit =
println(show(Book("Scala", 120)))Example
trait Describer[T]:
def describe(x: T): String
case class Book(title: String, pages: Int)
object Book:
given Describer[Book] with
def describe(b: Book): String = b.title + ":" + b.pages.toString
given String = "Found "
@main def main(): Unit =
println(summon[String] + summon[Describer[Book]].describe(Book("Scala", 120)))Key points
- Companion object: an object with the same name as a type, written beside that type.
- Type class: a trait that describes an ability a type can have.
- Companion lookup: a given in a type's companion object is found with no import.
- Current scope: the code around the call, including givens written in the same file.
- Using parameter: a parameter the compiler fills with a given value when the call leaves it out.
In this example, the trait describes what a Describer does. The case class Book holds a title and a page count. Its companion object gives the Describer for Book. A top-level given word sits in the current scope. The program prints that word followed by the description of a Book.
Note
two givens of the same type in scope make summon fail, so scopes matter.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
Where can the compiler find a given with no import?