google / google/auto

AutoValue: Allow using a Comparator for fluent building

Open
#1,910 3 comments 0 reactions 1 assignee Claimed by @eamonnmcmanus View on GitHub
Component: value P3 type=documentation
Dominant language
Java
Stars
10.6k
Forks
1.2k
Avg merge
6h 32m
Merged PRs (30d)
13

Description

Hello!
I am using AutoValue `1.11.0` (and Java 21) and I'm trying to use an `ImmutableSortedSet` in an `AutoValue`, and that has an `AutoValue.Builder`. I'd like to pass in a `Comparator` so that I can decide how the set gets ordered.

I'm also really fond of the fluent builder style, and I've been using what is described [here in the builders how-to](https://github.com/google/auto/blob/main/value/userguide/builders-howto.md#add).

However, that breaks when I'm trying to use a `Comparator`. The generated code (rightly) does not let me call `ImmutableSortedSet.Builder elementsBuilder(Comparator comparator)` more than once. The pattern given in the how-to, however, would have me do that. I've tried having it also generate a `ImmutableSortedSet.Builder elementsBuilder()`, but if both are present, it only generates the no-arg method.

I can see some workarounds, and I'm probably going to try them in the meantime.

- Caching the `elementsBuilder` in the abstract class
- I'm the one writing the `Element` class in this case, so I could implement `Comparable` (could get messy with inheritances though)
- Having my "fluent" accumulator accept some `Consumer>` argument?
- "Break the chain" and just let whoever is using the builder have to hold their own references

I can see trying to generate both the one-arg and the no-arg methods getting messy because it wouldn't be possible to really enforce which gets called first/which to initialize the sub-builder with. I'm not sure about other possible generated solutions.

Is there an official recommendation for how to do this, or documentation that I missed reading? I've read through [984](https://github.com/google/auto/issues/984) and friends, but I haven't found anything mixing the one-arg constructor and the fluent builder.

Thank you for your help!

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.