Rex Kerr
2 min readMar 10, 2023

--

Scala 3 givens (the heir of Scala 2 implicits) provides implicit context, explicit context, lack of context (NotGiven), context computed from other context, and context that overrides existing context. And first-class lambdas that take context.

It's also possible, with a little effort, to encode removal of context. (For instance, you can have a dummy type parameter that you use an inline match on, with a compile-time error for the "I turned this off" branch--not exactly without, but equivalent for most purposes.) But most of the time you can control that other ways, given how many tools there are to sculpt context.

And while you can't write methods that take context that they infer from what's inside them, you also can't write methods that take arguments that they infer from what's inside them...and that's probably a good thing. One of the biggest downsides of context is figuring out where it all came from and if a method doesn't even document that it takes it, it's kind of a nightmare. (Actually, you can do this with inlining--this is the same trick that lets you encode context removal--but it's really a bad idea because it makes it too hard to follow the flow of data.) It's the same thing that makes MacWire-style dependency injection awesome in theory and a complete disaster in (most) practice.

There is a halfway version, however. You can abstract the context that a particular method takes--say foo takes FooCtx--and then have FooCtx built out of a different set of givens itself. Somewhere along the chain you're going to have to actually come up with the givens that you need for a FooCtx, but if you're just passing stuff along a chain, the FooCtx can go along for the ride. It's a nice compromise between inscrutable data flow and endless tedium when you're rapidly changing requirements.

So maybe it's not all quite perfectly there, but it's very close (and I'd argue that some of what you're after isn't a very good idea for readability).

With Scala 3 especially, I've never felt myself at a lack for being able to express to the compiler what context I want. This may be partly personality: I lean somewhat towards being explicit. But it's also really powerful.

--

--

Rex Kerr
Rex Kerr

Written by Rex Kerr

One who rejoices when everything is made as simple as possible, but no simpler. Sayer of things that may be wrong, but not so bad that they're not even wrong.

No responses yet