What is a “context parameter” in Scala 3 (Dotty)?

The current Dotty (Scala 3) documentation uses the term context parameter in many places, but I haven’t seen a formal definition of it anywhere. After a little bit of research, here’s a Dotty “context parameter” definition that I pieced together from several different pages:

  • A context parameter is a parameter to a method or function.
  • As the name “context” implies, the parameter is contextual, meaning that it has some context to it.
  • Usually we think of context as being related to our current environment or actions, and that seems to be the case with context parameters.
  • For example, Martin Odersky writes, “For instance in the Dotty compiler, almost every function takes an implicit context parameter which defines all elements relating to the current state of the compilation.”
  • In the real world, if you’re at the zoo, your context is “I’m at the zoo right now.” So if someone says they see a gorilla, it’s not a total surprise to you.
  • Possibly the most important thing to know is that a context parameter is typically an implicit parameter, or at least what we call an implicit parameter with Scala 2.

In regards to that last point, ord in the following example is considered to be a context parameter:

def max[T](x: T, y: T)(using ord: Ord[T]): T =
    if ord.compare(x, y) < 0 then y else x

In that example (from the Dotty “using” page) it’s assumed that there is an implicit variable in the current environment of this code (i.e., the context of where this function is declared) of the type Ord[T], and in Dotty that variable was declared with the new given syntax.

For example, the Dotty “given” page uses this example to define an Ord[Int]:

trait Ord[T]:
    def compare(x: T, y: T): Int
    def (x: T) < (y: T) = compare(x, y) < 0
    def (x: T) > (y: T) = compare(x, y) > 0

given intOrd as Ord[Int]:
    def compare(x: Int, y: Int) =
        if (x < y) -1 else if (x > y) +1 else 0

From “implicit” to “given” and “using”

I hope that example isn’t too scary. From what I’ve read so far, in these examples the new keywords given and using are just replacements for some Scala 2 implicit uses. For example, this Dotty example:

def max[T](x: T, y: T)(using ord: Ord[T]): T

is equivalent to this Scala 2 example:

def max[T](x: T, y: T)(implicit ord: Ord[T]): T

(Credit: Someone else wrote that comparison. I have it in my notes, but I didn’t note who originally wrote it.)

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

Summary: Context parameters

In summary, if you wondered what context parameters are in Dotty and Scala 3, I hope this discussion is helpful.