How to set superclass properties in @Immutable classes?

Considering

import groovy.transform.Immutable

class A {
  String a
}

@Immutable
class B extends A {
  String b
}

When I try to set values ​​using the map constructor

def b = new B(a: "a", b: "b")

then aist still null:

groovy:000> b = new B(a: "a", b: "b")
===> B(b)
groovy:000> b.b
===> b
groovy:000> b.a
===> null

Is it possible to define a class @Immutablethat considers the properties of its superclasses in the map constructor?

I am using Groovy 2.4.3

+4
source share
1 answer

Based on the ImmutableASTTransformation code, the Map-arg constructor added by the method createConstructorMapCommondoes not include a call super(args)in the method body.

, ; , , , . - @Delegate, A.

import groovy.transform.*

@TupleConstructor
class A {
  String a
}

@Immutable(knownImmutableClasses=[A])
class B {
  @Delegate A base
  String b
}

def b = new B(base: new A("a"), b: "b")
println b.a

, A ( @Immutable, B , ,

b.a = 'foo' // succeeds
+3

Source: https://habr.com/ru/post/1619224/


All Articles