Skip to content

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 castings are performed when the type is specified both implicitly and explicitly.

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

An implicit casting is performed in the first part of the method main. The field symbol <fs1> is fully typed with the local program type t_date. The field sy-datum can be handled as a structure using the addition CASTING of the statement ASSIGN. This assignment would not be possible without the CASTING addition, since sy-datum is not compatible with the type of the field symbol.

An implicit casting is performed in the second part of the method main. The field symbol <fs2> is fully generic. A cast is performed to the local program type t_date for the field sy-datum using the addition CASTING of the statement ASSIGN. The field symbol <fs2> can now be handled like a structure but does not recognize components. For this reason, it must be assigned to a further field symbol <fs3>, component by component.