ABAP Traps: Don’t self-reference in constructor operators
Just a short heads up on a bit of unexpected ABAP behaviour when using VALUE: Developers are used to assigning a variable’s content to itself, as in x = x + 1. This will not work with VALUE!
A quick test shows what happens:
types: begin of ty_struct, val type i, end of ty_struct. data(struct) = value ty_struct( val = 8 ). write / struct-val. " -> 8 struct = VALUE #( val = struct-val + 1 ). write / struct-val. " -> not 9, but 1
Another related scenario would be to partially clear a structure. The following is a tempting way to do it but unfortunately will just result in an empty structure:
"Keep only F5 and F7, clear the rest: struct = VALUE #( f5 = struct-f5 f7 = struct-f7 ). "values are lost, struct is empty
Examining the documentation closely, we can read:
If the VALUE operator is used as the source of an assignment to a structure, this structure is first initialized after any LET expressions are evaluated or the structure is first assigned the data object dobj after BASE. The assignments are then executed directly in the parenthesis, with the structure components as target fields. (my emphasis)
So it’s “working as designed”, just not as expected.