Retrofit2: How to properly check the validity of response.body()?

Viewed 4865

Since version retrofit2.retrofit:2.3.0 I'm getting NullPointerException warnings on response.body() even when checking the body for null before:

Image

Method invocation 'getCar()' may produce 'java.lang.NullPointerException'

In the changelog for 2.3.0 was an entry related to null checks:

Retrofit now uses @Nullable to annotate all possibly-null values. [...] We use @ParametersAreNonnullByDefault and all parameters and return types are never null unless explicitly annotated @Nullable.

It that the intended behavior? In my point of view response.body() should be immutable, so my check in Picture 1 should not show a warning.

This is not a question about NullPointerExceptions - it's about the way how to handle responses of Retrofit2 properly. To not have warnings at the moment I have to do something like this:

if(response != null) {
    CarResponseBody body = response.body();
    if (body != null && body.getCar() != null){
        CarResponse car = body.getCar();
    }
}

A lot of code to just check if there is a valid response...

3 Answers
Related