SAP NetWeaver AS ABAP Release 740, ©Copyright 2014 SAP AG. All rights reserved.
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.
Source Code
REPORT demo_field_symbols_casting.
CLASS demo DEFINITION.
PUBLIC SECTION.
CLASS-METHODS main.
ENDCLASS.
CLASS demo IMPLEMENTATION.
METHOD main.
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( ).
*------- Casting with implicit typing ------------
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( ).
*------- Casting with explicit typing ------------
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( ).
ENDMETHOD.
ENDCLASS.
START-OF-SELECTION.
demo=>main( ).
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>.