Skip to content

Commit

Permalink
Merge pull request #4117 from square/jw.public-optional.2024-03-27
Browse files Browse the repository at this point in the history
Make optional converter public
  • Loading branch information
JakeWharton committed Mar 27, 2024
2 parents c579693 + d6eac54 commit eba9567
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

**Changed**

- Nothing yet!
- The built-in `OptionalConverterFactory` is now public to allow installing it before other converters which consume all types (e.g., Moshi, Gson, Jackson, etc.).

**Fixed**

Expand Down
19 changes: 17 additions & 2 deletions retrofit/src/main/java/retrofit2/OptionalConverterFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,24 @@
import okhttp3.ResponseBody;
import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement;

/**
* A {@link Converter.Factory} which supports Java's {@link Optional} to wrap null values from
* another converter.
* <p>
* This factory is installed by default on the JVM and Android API 24+. If you are using another
* converter which tries to serialize all types, such as Moshi or Gson, the default installation
* of this factory never gets a chance to run. To work around this, you can explicitly install this
* factory before your serialization library converter.
*/
@IgnoreJRERequirement // Only added when Optional is available (Java 8+ / Android API 24+).
@TargetApi(24)
final class OptionalConverterFactory extends Converter.Factory {
public final class OptionalConverterFactory extends Converter.Factory {
public static OptionalConverterFactory create() {
return new OptionalConverterFactory();
}

OptionalConverterFactory() {}

@Override
public @Nullable Converter<ResponseBody, ?> responseBodyConverter(
Type type, Annotation[] annotations, Retrofit retrofit) {
Expand All @@ -43,7 +58,7 @@ final class OptionalConverterFactory extends Converter.Factory {

@IgnoreJRERequirement
static final class OptionalConverter<T> implements Converter<ResponseBody, Optional<T>> {
final Converter<ResponseBody, T> delegate;
private final Converter<ResponseBody, T> delegate;

OptionalConverter(Converter<ResponseBody, T> delegate) {
this.delegate = delegate;
Expand Down

0 comments on commit eba9567

Please sign in to comment.