Repository navigation
Replies: 1 comment
|
This is implemented on main now and available in latest snapshots, would love if folks could give it a spin! |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Context
Some interfaces have one implementation per type argument, like
Encoder<T>,Comparator<T>, orDiffUtil.ItemCallback<T>. Sometimes these even compose, like anEncoder<List<User>>wrapping anEncoder<User>.Metro already supports generics in two places:
@Injectclass resolves for any requested type argument, so a request forBox<String>calls theBox<T>constructor withT = String@Includes, likeTypedBindings<Int>, has its type arguments substituted into its providers.@Providesand@Bindsfunctions can't have type parameters though, so eachEncodercombination currently needs its own binding.The usual alternative to this is a runtime registry, like Moshi's
JsonAdapter.Factory. A registry covers every type with one entry, but a missing entry fails at runtime.Proposal
Allow type parameters on
@Providesand@Bindsfunctions when Metro can infer them from the return type. When a graph requests a key that has no ordinary binding, Metro looks for a generic provider whose raw return type matches the key's raw type. If it can infer the type arguments and use the provider for that key, it creates a derived binding. The provider's parameters resolve the same way, so generic providers compose.Example
This example encodes teams to JSON with kotlinx.serialization's
JsonElementtypes.Encoder<T>is the type class.JsonEncodersholds the base encoders and the generic providers that compose them.Encoders for model types are ordinary injected classes and can request the composed encoders they need.
Consumers can also request concrete keys as usual.
Metro generates the equivalent of this:
Without generic providers, this graph needs five more hand-written providers; one for each composed key like
Encoder<String?>orEncoder<Map<String, List<User>>>. Each new model type or field type adds more.Declarations
Generic providers otherwise work like other
@Providesand@Bindsfunctions. They can have qualifiers, scopes, and context parameters. They live in binding containers and graphs and cooperate withincludes,contributes, andexcludesaggregation rules.A generic
@Bindsbinds a generic@Injectclass to an interface:Metro checks three things at the declaration:
T, because it would match every key and that's nonsense.@IntoSetor@IntoMap.Resolution
Metro picks a binding for a key in the following order.
Encoder<List<T>>is more specific thanEncoder<T>.@Injectclasses, as today.Matching uses the same exact type rules as other Metro keys (i.e. return type of
Encoder<T?>matches only nullable type arguments).After Metro picks a generic provider, its parameters must resolve. If they don't, Metro reports the missing binding. It doesn't try another provider, so each error points at one chain.
Some projects may want overlapping providers to be an error instead, so this would introduce a new
derivedBindingOverlapSeverityoption reports every key where step 3 had to choose.Reified type parameters
Metro already supports
inlineproviders. A generic one can also havereifiedtype parameters.With this,
Encoder<Order>works without a hand-written binding.UserEncoderstill wins forEncoder<User>, andliststill wins forEncoder<List<Order>>.The graph must be able to call a reified provider, so it must be public or
@PublishedApi internal.Scoping and graph extensions
Each derived binding has its own type key in the graph. A scoped generic provider scopes each one separately. With
@SingleIn(AppScope::class) @Provides fun <T> cache(): Cache<T>,Cache<User>andCache<Order>are two singletons.A graph extension can also use its parents' generic providers and a scoped derived binding lives in the graph that owns its scope, like a scoped
@Injectclass does today.Cycles
Recursive types can create ordinary cycles and a deferrable parameter type (e.g. function,
Lazy) breaks them as it does today. An encoder fordata class Category(val children: List)would need to take() -> Encoder<List>`.A generic provider can also recurse without repeating a key, like
@Provides fun <T> wrapped(inner: Encoder<List<T>>): Encoder<T>. Metro reports an error when a chain applies the same provider to a key that keeps growing and uses a depth limit as a backstop.Implementation
Internally, Metro treats a generic provider as a transforming provider. A transforming provider takes a requested key and returns a binding for that key, or nothing if the key doesn't match.
Metro already does both halves of this.
BindingLookupcreates bindings for generic@Injectclasses on demand. It substitutes the requested type arguments withdeepRemapperForand caches one binding per key.BindingContainer.withTypeSubstitutionsubstitutes a generic container's type arguments into its providers withProviderFactory.withRemappedTypesandBindsCallable.remapTypes.A transforming provider takes its type arguments from the requested key, like an
@Injectclass and applies them to a provider like a generic container.FIR
BindingContainerCallableCheckerallows type parameters on@Providesand@Binds, and adds the three declaration checks.BindingContainerCallableCheckerturns the existing inline visibility warnings into errors. It also skips the scoped inline warning, because these providers are onlyinlineto allowreified.ProvidesFactoryFirGeneratorcopies the function's type parameters onto the factory class.IR
selectBindinggets a new stage after the registered, multibinding, and optional stages, and before class lookup. The stage matches the key against the index and picks a provider. Then it builds a remapper from the inferred type arguments and creates an ordinaryIrBinding.ProvidedorIrBinding.Aliasfor the key. These instance do get cached in the regular bindings cache under their finalized key.selectBindingwould live inmetro-commonso the IDE plugin'sKaBindingSelectioncan reuse it. The IDE plugin needs its own index of generic providers for that stage.After step 2, nothing downstream knows that a binding was derived 🎉. Graph reports label derived bindings with their provider and type arguments.
Generic providers share one factory class through erasure, like generic
@Injectclasses do today. Reified providers get a factory class too, so other modules find them the same way. ItsnewInstance()already copiesinlinefrom the provider, and it would copyreifiedas well. The factory'sinvoke()can't callnewInstance(), though, because a class's type parameters can't be reified.So the graph always calls a reified provider directly, with the concrete type arguments. When it needs a provider instance, like for
() -> Encoder<Order>or a scoped binding, it wraps the direct call in a lambda. Suspend bindings already work this way, because their factories can't serve as aSuspendProvider.Prior art
KEEP-87
KEEP-87 proposed type classes for Kotlin in 2017 via
extensiondeclarations for instances andwithparameters that the compiler would fill. The Kotlin team closed it in 2020 and later shipped context parameters. Context parameters pass instances along, but the caller still has to find them.The idea of composing instances from other instances at compile time is part of the inspiration for this proposal though. The KEEP's main example looks similar with generic providers.
The scope is much smaller though. KEEP-87 was a language feature for any call site whereas derived bindings obviously only apply to code that Metro injects. Most of KEEP-87's design went into where the compiler should search for instances and how to keep them coherent across libraries though, and Metro sidesteps that because a graph already has an explicit set of bindings.
Other languages and frameworks
impl<T: Display> ToString for T. Overlap is an error. Resolution stops atrecursion_limit.ERRORmatches Rust's behavior.extension Array: Equatable where Element: Equatable.listgivesList<T>an encoder only whenThas one.Box.serializer(User.serializer())for generic classes.AddSingleton(typeof(ILogger<>), typeof(Logger<>)), which the container fills in for each requested type at runtime. A registration for an exact type likeILogger<Foo>wins over an open one. Among open ones, the last registration wins.@Provides.Open questions
Treturn types IFF we require a qualifier?Possible future/related ideas
UserEncoderdoesn't need to be written by hand. Metro would resolve an encoder for each property and pass them to one library-written function that combines them. Scala 3'sderivesworks this way, and kotlinx.serialization's plugin does something similar for@Serializableclasses.fun createLoginScreen(token: UserToken): LoginScreen. These need runtime inputs, so they fit better with graph extensions than with derived bindings.All reactions