ABAP Keyword Documentation → ABAP - Reference → Processing Internal Data → Assignments → Assigning References → Setting Field Symbols → ASSIGN → ASSIGN - casting_spec → Casting Examples
Field Symbols - Casting
This example demonstrates how casting with implicit and explicit type specification is carried out.
Other versions: 7.31 | 7.40 | 7.54
Source Code
TYPES: BEGIN OF t_date,
year TYPE n LENGTH 4,
month TYPE n LENGTH 2,
day TYPE n LENGTH 2,
END OF t_date.
FIELD-SYMBOLS: <fs1> TYPE t_date,
<fs2> TYPE any,
<fs3> TYPE n.
DATA(out) = cl_demo_output=>new(
)->write_text( |sy-datum: { sy-datum }|
)->line( ).
<span class="blue">*------- Casting with implicit typing ------------</span>
ASSIGN sy-datum TO <fs1> CASTING.
out->write_text( |Year: { <fs1>-year }| ).
out->write_text( |Month: { <fs1>-month }| ).
out->write_text( |Day: { <fs1>-day }| ).
out->line( ).
<span class="blue">*------- Casting with explicit typing ------------</span>
ASSIGN sy-datum TO <fs2> CASTING TYPE t_date.
DO.
ASSIGN COMPONENT sy-index OF STRUCTURE <fs2> TO <fs3>.
IF sy-subrc <> 0.
EXIT.
ENDIF.
out->write_text( |Component { sy-index }: { <fs3> }| ).
ENDDO.
out->display( ).
Description
In the first part of the main
method, an implicit casting is carried out.
The field symbol <fs1>
is completely typed with the local program type
t_date
. Using the CASTING
addition of the
ASSIGN statement, the field sy-datum
can be treated as a structure.
Without the CASTING
addition assigning would not be possible, because sy-datum
is not compatible with the type of the field symbol.
In the second part of the main
method, an implicit casting is carried out.
The field symbol <fs2>
is completely generic. Using the CASTING
addition of the ASSIGN
statement, a cast is carried out for the field
sy-datum of the local program type t_date
. The field symbol
<fs2> can now be treated like a structure but does not recognize components. For this reason, it must be assigned component by component to a further field symbol <fs3>
.