The 'Given Defaults Pattern': How to Implement Class Defaults with a Macro in Scala 3 :: Jun 23, 2023
The database client Magnum has Repositories, which derive common SQL statements like findById, insert, and update at compile-time.
How does this work? One might think that Repo.apply is a macro, but it’s not. Instead, Repo is an open class designed for extension. Users can subclass Repo (or its supertype ImmutableRepo) to encapsulate and organize their queries:
The way Repositories work in Magnum is by the ‘Given Defaults’ pattern. Looking at the definition of ImmutableRepo, we see it requires a given RepoDefaults parameter.
RepoDefaults is a trait that implements the default behavior of the Repo. If a user seeks to override any methods, they are free to do so.
When compiling val userRepo = Repo[User, User, Long] or similar, Scala’s implicit search looks for a given RepoDefault in the companion object, and finds the Scala 3 macro.
Conclusions
The UX of this pattern is incredible and is appropriate for any Macro that wants to allow user extension.