Skip to content

Commit

Permalink
Allow boxed @autovalue properties to be set from the corresponding pr…
Browse files Browse the repository at this point in the history
…imitive type.

We also allow the converse, though that's less likely to be useful.

RELNOTES=Allow boxed @autovalue properties to be set from the corresponding primitive type.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=309320843
  • Loading branch information
eamonnmcmanus authored and cpovirk committed May 1, 2020
1 parent d6e56d3 commit 2bbe506
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -1570,6 +1570,51 @@ public void testOmitNullableWithBuilder() {
}
}

@AutoValue
public abstract static class PrimitiveAndBoxed {
public abstract int anInt();

@Nullable
public abstract Integer aNullableInteger();

public abstract Integer aNonNullableInteger();

public abstract Builder toBuilder();

public static Builder builder() {
return new AutoValue_AutoValueTest_PrimitiveAndBoxed.Builder();
}

@AutoValue.Builder
public interface Builder {
Builder setAnInt(Integer x);

Builder setANullableInteger(int x);

Builder setANonNullableInteger(int x);

PrimitiveAndBoxed build();
}
}

@Test
public void testPrimitiveAndBoxed() {
PrimitiveAndBoxed instance1 =
PrimitiveAndBoxed.builder().setAnInt(17).setANonNullableInteger(23).build();
assertThat(instance1.anInt()).isEqualTo(17);
assertThat(instance1.aNullableInteger()).isNull();
assertThat(instance1.aNonNullableInteger()).isEqualTo(23);

PrimitiveAndBoxed instance2 = instance1.toBuilder().setANullableInteger(5).build();
assertThat(instance2.aNullableInteger()).isEqualTo(5);

try {
instance1.toBuilder().setAnInt(null);
fail();
} catch (NullPointerException expected) {
}
}

@AutoValue
public abstract static class OptionalPropertiesWithBuilder {
public abstract com.google.common.base.Optional<String> optionalString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,11 @@ private Optional<Function<String, String>> getSetterFunction(
MoreTypes.asExecutable(
typeUtils.asMemberOf(MoreTypes.asDeclared(builderType.asType()), setter));
TypeMirror parameterType = finalSetter.getParameterTypes().get(0);
if (typeUtils.isSameType(parameterType, targetType)) {
// Two types are assignable to each other if they are the same type, or if one is primitive and
// the other is the corresponding boxed type. There might be other cases where this is true, but
// we're likely to want to accept those too.
if (typeUtils.isAssignable(parameterType, targetType)
&& typeUtils.isAssignable(targetType, parameterType)) {
if (nullableParameter) {
boolean nullableProperty =
nullableAnnotationFor(valueGetter, valueGetter.getReturnType()).isPresent();
Expand Down

0 comments on commit 2bbe506

Please sign in to comment.