Named parameter constructor in groovy and lombok @Value

pixel :

I have following object annotated with @Value from Lombok:

@Value
public class Foo {
    private final boolean bar;
    private final boolean baz;
    private final boolean boo;
}

I try to instantiate Foo from groovy test:

new Foo(bar: true, baz: false, boo: true)

but I get warning:

Constructor 'Foo' cannot be applied to '()'

and during runtime following error:

Cannot set readonly property: bar for a class: Foo

is there a way to use named constructor in groovy that will call constructor with all arguments instead of calling empty constructor and then trying to set fields?

Alex :
Constructor 'Foo' cannot be applied to '()'

This appears because all fields in your class are final, so you have to initiate these fields during object initialization.

So the only way to create an object of this class is to use all-args constructor:

new Foo(true, false, true)

Due to the way, Groovy handles what looks like named arguments (Groovy does not support named arguments - it passes a Map), this will also fail with similar Groovy code. The way Groovy handles the map passing here, is by unrolling the map into setter calls (and there are none because the attributes are final).

@groovy.transform.TupleConstructor
class Foo {
    final boolean bar
    final boolean baz
    final boolean boo
}

new Foo(bar: true, baz: false, boo: true)

Fails with

Caught: groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: bar for class: Foo
groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: bar for class: Foo
        at x.run(x.groovy:8)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=76844&siteId=1