Given Imports
Given imports bring given values from another object into scope. A given value is a value the compiler can find on its own when a program needs it.
An import brings a given into scope
Loud holds a level of 8 as a given value. The import makes that value available to summon.
object Loud:
given Int = 8
@main def main(): Unit =
import Loud.given
println(summon[Int])A different object gives a different result
Quiet holds a level of 2. Importing Quiet instead of Loud changes the summoned number.
object Quiet:
given Int = 2
@main def main(): Unit =
import Quiet.given
println(summon[Int])A selective import brings one given type
Defaults holds a number and a word. The selective import brings only the number.
object Defaults:
given Int = 6
given String = "hi"
@main def main(): Unit =
import Defaults.{given Int}
println(summon[Int])Example
object Loud:
given Int = 8
object Quiet:
given Int = 2
@main def main(): Unit =
import Loud.given
println(summon[Int])
println(summon[Int] * 3)Key points
- Given import: an import that brings only given values into scope.
- Object: a named holder for values and givens.
- All givens: one import can bring every given from an object at once.
- Selective import: an import that brings one given type and leaves the rest behind.
- Changed result: a different imported given gives a different summoned result.
In this example, Loud holds 8 and Quiet holds 2. The import brings only the given from Loud into scope. The first print shows the summoned number. The second print shows that number times 3.
Note
an imported given works only inside the block where the import sits.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does import Loud.given do?