Retrofit optional and required fields

I have stuck in the question several hours and finally resolve the question.

I' ll use Kotlin to answer the question.

As @Ryan said, you can also just pass null as the value in Kotlin:

fun getStuff(@Query("user_id") userId: String? = null ,
                 @Query("password") password: String? = null,
                 @FieldMap options: Map<String, String>? = null): Call<Response>

If you have a optional fields like @Query("page") int page in Java, there is something that you should keep in mind:

In Java, you can’t pass null for primitive data types like int, float, long, etc.

Instead, use Integer, Float, Long, etc and the compiler won’t be grumpy.

So the correct answer is: @Query("page") Integer page.

And in Kotlin, you can’t pass null for primitive data types like Int, Float, Long, etc.

Using Int? instead of Int and Retrofit will ignore them while assembling the request.

This is because while Kotlin compile on the JVM, non-nullable values of this type are represented as values of the primitive type int, nullable value like Int? is a boxed Type.

So in Kotlin, a nullable Int Int? can solve this question.

For more information about Kotlin primitive, see: What is the difference between Int and Integer in Kotlin?

I hope it helped somebody also.


@FieldMap and @Query params both support optional fields. As you mentioned, simply pass null if you don't want to pass a value.