Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accessor methods in Builders? #234

Closed
jhorsley opened this issue Jan 11, 2016 · 2 comments
Closed

Accessor methods in Builders? #234

jhorsley opened this issue Jan 11, 2016 · 2 comments

Comments

@jhorsley
Copy link

I couldn't see a way to have accessors automatically generated in the builder. I have some use cases where I pass a Builder to other methods to set various values and it's helpful for those methods to check existing Builder state. Is this currently possible?

@elucash
Copy link
Member

elucash commented Jan 11, 2016

Thank you for the issue report! We have a solution for that in form of a modifiable companion classes http://immutables.github.io/immutable.html#modifiable . We were trying to not make builders too heavy, and often along with having accessors it is useful so that "builder" could implement abstract value type (things like buildPartial on builder are considered harmful), making modifiable classes more useful for sophisticated building sequences, including copy/clear/reset etc. If you actually want it to be like builder, you can use styles to masquerade modifiable class to have naming conventions of a typical builder

@Value.Style(
   typeModifiable = "*Builder", // modifiable will be generated as "FooBuilder"
   toImmutable = "build",  // rename "toImmutable" method to "build"
   set = "*", // adjust to your taste: setters with no prefixes like in default builders.
   create = "new", // plain constructor to create builder, just as example
)  // style could also put on package or as meta annotation
@Value.Modifiable
@Value.Immutable
public abstract class Foo {
   public abstract String getName();
   public abstract List<Integer> getCounts();
   public static FooBuilder builder() {  // just for convenience, can create builder directly
      return new FooBuilder();
   }
}

FooBuilder builder = Foo.builder()
    .name("Name");

String name = builder.getName();
boolean nameIsSet = builder.nameIsSet();

Foo foo = builder.build();

// with default styles it would look more like this

ModifiableFoo foo = ModifiableFoo.create()
   .setName("Name");
String name = foo.getName();
boolean nameIsSet = foo.nameIsSet();
ImmutableFoo immutableFoo = foo.toImmutable()

@jhorsley
Copy link
Author

Nice! Looks like this should do exactly what I need. Many thanks for the super fast reply.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants