javax.validation.constraints.NotNull), also started annotating the relevant methods with it.But.
When using the new Java 8 Streams API, Eclipse warns inside the functions you toss in, even if you've filtered out the null ones.
I'll give you an example:
// ...inside the Foo class...
public Foo(@NotNull final Bar bar) {
this.bar = Objects.requireNonNull(bar, "Shame...");
}
// ...inside somewhere completely unrelated...
public Optional<Foo> getFoobarizedBarBaz() {
return Optional.ofNullable(
fooService.getBar()
.stream()
.filter(Objects::nonNull) // yeah, so no nulls, plz
.map(bar -> new Foo(bar /* Oh no, yellow underline*/, someLocalValue)
.findAny());
}
But oh, the "bar" is underlined, stating "Null type safety: The expression of type 'Bar' needs unchecked conversion to conform to '@NotNull Bar'"...
If only there were a way to resolve that...wait, there is! We can set the type of the formal parameters inside the lambda expression!
// ...inside somewhere completely unrelated...
public Optional<Foo> getFoobarizedBarBaz() {
return Optional.ofNullable(
fooService.getBar()
.stream()
.filter(Objects::nonNull)
.map((@NotNull Bar bar) -> new Foo(bar, someLocalValue)
.findAny());
}
Formal parameters. PARAMETERS.
@NotNull's @Target annotation includes PARAMETER. Even it's comment states: "Formal parameter declaration".
Win.
No comments :
Post a Comment