google / google/built_value.dart

error calling replace(null) on nullable nested builders

Open
#754 3 comments 1 reaction 1 assignee Claimed by @davidmorgan View on GitHub
p2 / feature request
Dominant language
Dart
Stars
886
Forks
195
Avg merge
1d 11h
Merged PRs (30d)
4

Description

Related to [this question](https://github.com/google/built_collection.dart/issues/196) from built_collection issues:

> For nested collections the intended usage is `nums.replace([2, 3, 5, 7, 11])`

But what if the field is nullable? (This is unrelated to whether the field is a collection or not, which is why I ask it here.)

Suppose I have a built value class

```dart
abstract class NestedBuiltValue implements Built {
factory NestedBuiltValue([void Function(NestedBuiltValueBuilder) updates]) = _$NestedBuiltValue;
NestedBuiltValue._();
}
```

Suppose I include an instance of `NestedBuiltValue` as a field in another.

```dart
abstract class TestBuiltValue implements Built {
@nullable
NestedBuiltValue get nullable_nested;

factory TestBuiltValue(NestedBuiltValue nullable_nested) =>
TestBuiltValue.from((b) => b
..nullable_nested.replace(nullable_nested));

factory TestBuiltValue.from([void Function(TestBuiltValueBuilder) updates]) = _$TestBuiltValue;

TestBuiltValue._();
}
```

Then attempting to instantiate it gives an error at the line above where `replace` is called:

```dart
var v = TestBuiltValue(null); // throws "Invalid argument(s) (other): Must not be null"
```

But it works if I change the unnamed factory as follows (though it goes through `toBuilder()`):

```dart
factory TestBuiltValue(NestedBuiltValue nullable_nested) =>
TestBuiltValue.from((b) => b
..nullable_nested = nullable_nested?.toBuilder());
```

Is there a better practice than this for nullable fields?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.