OptionallyProvided

@Target(allowedTargets = [AnnotationTarget.CLASS])
annotation class OptionallyProvided(val inComponent: KClass<*> = Nothing::class)(source)

Denotes that the annotated type might not be provided to the dependency graph.

This will generate a @BindsOptionalOf binding for the annotated type.

This is useful when the type will only be provided under certain circumstances. For example an Android app might have some debug settings that are only available in debuggable builds.

Example

@OptionallyProvided
interface DebugApi

// This generates
@BindsOptionalOf
abstract fun bindsOptionalDebugApi(): DebugApi

// Then in your implementation module
@AutoBind
@Singleton
class RealDebugApi @Inject constructor() : DebugApi

Component

Auto Dagger tries to infer the component based on the scope of the object using the following mapping:

ScopeComponent
No scopeSingletonComponent
SingletonSingletonComponent
ReusableSingletonComponent
ActivityRetainedScopedActivityRetainedComponent
ActivityScopedActivityComponent
FragmentScopedFragmentComponent
ServiceScopedServiceComponent
ViewScopedViewComponent
ViewModelScopedViewModelComponent
ViewWithFragmentScopedViewWithFragmentComponent

If you want to install the binding in a different component or if you're using a custom scope, then you can use the inComponent parameter to explicit provide the component:

@OptionallyProvided(inComponent = SomeComponent::class)
interface DebugApi

Qualifiers

Any Qualifiers on the annotated type will be carried over to the binding:

@Named("Prod")
@OptionallyProvided
interface Authenticator

// Generates the equivalent to:
@BindsOptionalOf
@Named("Prod")
abstract fun bindsOptionalAuthenticator(): Authenticator

Since

1.3.0

Parameters

inComponent

Which component to install the binding in. Defaults to being inferred based on the scope.

See also

Properties

Link copied to clipboard