In many situations the name of a context parameter doesn’t have to be mentioned explicitly, since it’s only used by the compiler in synthesized arguments for other context parameters. In that case you don’t have to define a parameter name, and can just provide the parameter type.
Background
For example, this maximum
method takes a context parameter of type Ord
, only to pass it on as an argument to max
:
def maximum[A](xs: List[A])(using ord: Ord[A]): A =
xs.reduceLeft(max(ord))
In that code the parameter name ord
isn’t actually required; it can be passed on as an inferred argument to max
, so you just state that maximum
uses the type Ord[A]
without giving it a name:
def maximum[A](xs: List[A])(using Ord[A]): A =
xs.reduceLeft(max)
Context bounds
Given that background, a context bound is a shorthand syntax for expressing the pattern of, “a context parameter that depends on a type parameter.”
Using a context bound, the maximum
method can be written like this:
def maximum[A: Ord](xs: List[A]): A = xs.reduceLeft(max)
A bound like : Ord
on a type parameter A
of a method or class indicates a context parameter with Ord[A]
.
For more information about context bounds, see the “What are context bounds?” section of the Scala FAQ.
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
- 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
- Given Instances and Using Clauses
- 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