Skip to content

Commit 70f5a9a

Browse files
committed
Return an empty collection instead of null
The method `get<MemberName>OrEmpty()` for collections, either lists or maps, was supposed to return an empty collection when the collection was not set, instead of null, but somehow we missed to add this expected behavior. This change fixes this, if the collection was not set we return either `Collections.emptyList()` or `Collections.emptyMap()` depending on the collection type instead of `null`. The user can still find whether the value was set by using the `Optional<...> get<MemberName>()` variant that returns en empty optional when the collection was not set.
1 parent 2be4f24 commit 70f5a9a

File tree

1 file changed

+7
-2
lines changed
  • smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators

1 file changed

+7
-2
lines changed

smithy-trait-codegen/src/main/java/software/amazon/smithy/traitcodegen/generators/GetterGenerator.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
*/
55
package software.amazon.smithy.traitcodegen.generators;
66

7+
import java.util.Collections;
78
import java.util.Optional;
89
import software.amazon.smithy.codegen.core.Symbol;
910
import software.amazon.smithy.codegen.core.SymbolProvider;
@@ -136,12 +137,16 @@ public Void structureShape(StructureShape shape) {
136137
// If the member targets a collection shape and is optional then generate an unwrapped
137138
// getter as a convenience method as well.
138139
Shape target = model.expectShape(member.getTarget());
139-
if (target.isListShape() || target.isMapShape()) {
140+
boolean isListShape = target.isListShape();
141+
if (isListShape || target.isMapShape()) {
140142
writer.openBlock("public $T get$UOrEmpty() {",
141143
"}",
142144
symbolProvider.toSymbol(member),
143145
symbolProvider.toMemberName(member),
144-
() -> writer.write("return $L;", symbolProvider.toMemberName(member)));
146+
() -> writer.write("return $1L == null ? $2T.empty$3L() : $1L;",
147+
symbolProvider.toMemberName(member),
148+
Collections.class,
149+
isListShape ? "List" : "Map"));
145150
}
146151
} else {
147152
writer.openBlock("public $T get$U() {",

0 commit comments

Comments
 (0)