The following fails to compile:
@NotNull String defaultFormatter(@Nullable Object value) {
if (value instanceof Collection) {
return ((Collection) value).stream()
.map(MyClass::defaultFormatter)
.collect(Collectors.joining(eol));
}
return String.valueOf(value);
}
In particular, when compiled with javac, the error would be:
Error:(809, 94) java: incompatible types:
java.lang.Object cannot be converted to
@org.jetbrains.annotations.NotNull java.lang.String
But the following compiles just fine:
@NotNull String defaultFormatter(@Nullable Object value) {
if (value instanceof Collection) {
Stream<String> stream = ((Collection) value).stream()
.map(MyClass::defaultFormatter);
return stream.collect(Collectors.joining(eol));
}
return String.valueOf(value);
}
The only difference would be that I introduced an extra variable. Note that I didn't cast, so no semantic change.
Can anybody explain why is this needed?