Shadowing a module
Every module gets a generated shadow<Module> extension function, named after the module, which builds a new module on top of an existing one.
Like copy<Module>, it takes one parameter per member and you only name what you want to override.
Unlike a copy, the original module never sees your overrides:
val parent = MyModule(
name = Binding.value("John"),
hello = Binding.single { "Hello, $name" },
)
val child = parent.shadowMyModule(
name = Binding.value("Jane"),
)
child.name // "Jane"
child.hello // "Hello, John" (1)
| 1 | hello was not overridden, so the parent evaluates it, against itself. |
The name comes from lexical scoping: a name declared in the child hides the parent’s one for the child only.
Calling shadowMyModule() without any argument returns the very same module.
As with copies, a module can also call the shadow function of each of its @DIModule ancestors, which builds that ancestor (see Named after the module).
appModule.shadowAppModule(/…/) will be deprecated once companion extensions are stable in Kotlin (they are experimental in Kotlin 2.5).
It will then be replaced by AppModule.shadow(of = appModule, /…/), which is why a module member may not be named of.
|
These functions used to all be named shadow, which is still generated, but deprecated with an error that offers its shadow<Module> replacement.
The next version of Inara will no longer generate it.
|
How it differs from a copy
A copy gives the new module its own copy of every binding, each running against the new module. A shadow instead delegates to the parent for every member you omit, which evaluates it against itself:
-
a binding you override runs against the child, so it sees the child’s other overrides and the parent’s values for everything else;
-
a binding you do not override runs against the parent, so it never sees the overrides;
-
a
single,weakSingleormultiplexthat you do not override is built and memoized by the parent only, so the child and the parent always agree on its instance.
val copied = parent.copyMyModule(name = Binding.value("Jane"))
copied.hello // "Hello, Jane": the copy has its own `single`
Default implementations
For a member that has a default implementation, an omitted parameter delegates to the parent, whose body runs against the parent.
An explicit null runs the interface’s own body against the child, so it observes the overrides:
val child = parent.shadowMyModule(name = Binding.value("Jane"), greeting = null)
child.greeting() // "Hello, Jane"
Chaining shadows
A shadow is a module like any other, so it can be shadowed in turn. Each level delegates to the one below it:
val grandChild = child.shadowMyModule(name = Binding.value("Joan"))
Use copy<Module> to build a variant that works as a whole, with its own state, and shadow<Module> to override a few members while keeping the original in charge of everything else.
|