This doc page is specific to Scala 3, and may cover new concepts not available in Scala 2. Unless otherwise stated, all the code examples in this page assume you are using Scala 3.
To make it more clear where givens in the current scope are coming from, a special form of the import
statement is used to import given
instances.
The basic form is shown in this example:
object A:
class TC
given tc: TC = ???
def f(using TC) = ???
object B:
import A.* // import all non-given members
import A.given // import the given instance
In this code the import A.*
clause of object B
imports all members of A
except the given
instance, tc
.
Conversely, the second import, import A.given
, imports only that given
instance.
The two import
clauses can also be merged into one:
object B:
import A.{given, *}
Discussion
The wildcard selector *
brings all definitions other than givens or extensions into scope, whereas a given
selector brings all givens—including those resulting from extensions—into scope.
These rules have two main benefits:
- It’s more clear where givens in the current scope are coming from. In particular, it’s not possible to hide imported givens in a long list of other wildcard imports.
- It enables importing all givens without importing anything else. This is important because givens can be anonymous, so the usual use of named imports is not practical.
More examples of the “import given” syntax are shown in the Packaging and Imports chapter.
Contributors to this page:
Contents
- Introduction
- Scala Features
- Why Scala 3?
- A Taste of Scala
- Hello, World!
- The REPL
- Variables and Data Types
- Control Structures
- Domain Modeling
- Methods
- First-Class Functions
- Singleton Objects
- Collections
- Contextual Abstractions
- Toplevel Definitions
- Summary
- A First Look at Types
- String Interpolation
- Control Structures
- Domain Modeling
- Tools
- OOP Modeling
- FP Modeling
- Methods
- Method Features
- Main Methods in Scala 3
- Summary
- Functions
- Anonymous Functions
- Function Variables
- Eta-Expansion
- Higher-Order Functions
- Write Your Own map Method
- Creating a Method That Returns a Function
- Summary
- Packaging and Imports
- Scala Collections
- Collections Types
- Collections Methods
- Summary
- Functional Programming
- What is Functional Programming?
- Immutable Values
- Pure Functions
- Functions Are Values
- Functional Error Handling
- Summary
- Types and the Type System
- Inferred Types
- Generics
- Intersection Types
- Union Types
- Algebraic Data Types
- Variance
- Opaque Types
- Structural Types
- Dependent Function Types
- Other Types
- Contextual Abstractions
- Extension Methods
- Context Parameters
- Context Bounds
- Given Imports
- Type Classes
- Multiversal Equality
- Implicit Conversions
- Summary
- Concurrency
- Scala Tools
- Building and Testing Scala Projects with sbt
- Worksheets
- Interacting with Java
- Scala for Java Developers
- Scala for JavaScript Developers
- Scala for Python Developers
- Where To Go Next