Skip to content

Requiredness

Andy Boothe edited this page Jan 17, 2025 · 3 revisions

Requiredness is a Rapier-level concept that complements Dagger's nullability concept.

Dagger's Nullability

In Dagger, an injection site is "nullable" if it can receive no value. Dagger's nullability is opt-in, since it must be indicated using the @Nullable annotation. For example:

@Provides
@Nullable
public Foo provideFoo(@Nullable String foo) {
    return foo != null ? Foo.valueOf(foo) : null;
}

In this provider method, the foo parameter injection site is nullable because it is explicitly annotated with the @Nullable annotation. Note how the method body deals with the value of foo accordingly. However, in this example:

@Provides
public Bar provideBar(String bar) {
    return Bar.valueOf(bar);
}

In the provider method, the bar parameter injection site is not nullable because it is not annotated with the @Nullable annotation. Therefore, Dagger will not allow any calls to the provideBar provider method with a null value for bar.

Rapier's Requiredness

Many of Rapier's code generation annotations allow users to provide default values, e.g., @EnvironmentVariable. In Rapier, an injection site is "required" if it is not nullable and has no default value. For example:

@Provides
@Nullable
public Foo provideFoo(@Nullable @EnvironmentVariable("FOO") String foo) {
    return foo != null ? Foo.valueOf(foo) : null;
}

In this provider method, the foo parameter injection site is not required, since it is nullable. Similarly:

@Provides
public Foo provideFoo(@EnvironmentVariable(value="FOO", defaultValue="foo") String foo) {
    return Foo.valueOf(foo);
}

In this provider method, the foo injection site is not nullable, but it also is not required, since it has a default value. If the user does not provide a value for the FOO environment variable, then Rapier's generated code will provide the value of "foo" instead of null. However:

@Provides
public Foo provideFoo(@EnvironmentVariable(value="FOO") String foo) {
    return Foo.valueOf(foo);
}

In this provider method, the foo injection site is not nullable and required, since it has no default value. If the user does not provide a value for the FOO environment variable, then Rapier's generated code would throw an exception.

Clone this wiki locally