Member arguments
A Binding carries exactly one argument, of type A.
The parameters of a member decide what that argument is:
| Member | Binding type |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
One parameter
The argument is the parameter itself:
@DIModule
interface UserModule {
fun user(id: Int): User
}
UserModule(
user = Binding.factory { id -> User(id) },
)
A vararg parameter
A vararg parameter arrives as the array Kotlin builds for it: an Array<out T>, or a primitive array such as IntArray for primitive types.
@DIModule
interface PathModule {
fun path(vararg segments: String): String
}
PathModule(
path = Binding.factory { segments -> segments.joinToString("/") },
)
Multiple parameters
When a member takes two or more parameters, the processor generates a <Module>BindingArguments container, holding one data class per such member.
Each class is named after its member, capitalized, and has one property per parameter.
@DIModule
interface SearchModule {
fun index(): SearchIndex
fun search(query: String, limit: Int): List<SearchResult>
fun tagged(vararg tags: String, strict: Boolean = false): List<SearchResult>
}
generates:
public class SearchModuleBindingArguments private constructor() {
public data class Search(val query: String, val limit: Int)
@Suppress("ArrayInDataClass")
public data class Tagged(val tags: Array<out String>, val strict: Boolean)
}
The binding receives an instance of that class:
SearchModule(
index = Binding.single { SearchIndex() },
search = Binding.factory { args -> index().find(args.query).take(args.limit) },
tagged = Binding.factory { args -> index().findTagged(args.tags.toSet(), args.strict) },
)
Because the arguments classes are data classes, they can serve as multiplex keys, as long as they hold no array (see the warning in multiplex).
An arguments class belongs to the module that declares the member.
A module that inherits the member from another @DIModule uses that module’s class, and generates none of its own:
@DIModule
interface AppModule : SearchModule
AppModule(
index = Binding.single { SearchIndex() },
search = Binding.factory { args: SearchModuleBindingArguments.Search -> index().find(args.query).take(args.limit) }, (1)
tagged = Binding.factory { args -> index().findTagged(args.tags.toSet(), args.strict) },
)
| 1 | SearchModuleBindingArguments, not AppModuleBindingArguments: a binding built for SearchModule therefore fits AppModule as it is, which is what lets composition reuse it. |
A member that comes from an interface that is not a @DIModule (see Extending plain interfaces) gets its class in the first @DIModule that extends that interface.