Skip to Content
1
Mar 14, 2021 at 06:06 AM

ABAP Loop Strange behaviour (bug?)

65 Views Last edit Mar 14, 2021 at 07:19 AM 5 rev

Hi!

When you start this code:

CLASS lcl_app DEFINITION.
  PUBLIC SECTION.
    TYPES tt_data TYPE STANDARD TABLE OF i WITH EMPTY KEY.
    DATA mt_data TYPE tt_data.

    METHODS: change_data,

    get_reference
      RETURNING VALUE(ro_data) TYPE REF TO lcl_app.

    METHODS print.
ENDCLASS.

CLASS lcl_app IMPLEMENTATION.

  METHOD change_data.
    LOOP AT get_reference( )->mt_data ASSIGNING FIELD-SYMBOL(<lv_value>).
      <lv_value> = <lv_value> + 1.
    ENDLOOP.
  ENDMETHOD.

  METHOD get_reference.
    ro_data = me.
  ENDMETHOD.

  METHOD print.
    LOOP AT mt_data INTO DATA(lv_value).
      WRITE: / lv_value.
    ENDLOOP.
    ULINE.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  DATA(lo_app) = NEW lcl_app( ).
  lo_app->mt_data = VALUE #( ( 1 ) ).

  lo_app->change_data( ).
  lo_app->print( ).

You will see that mt_data is not changed. Сan anyone explain why?

If you change code to this:

  METHOD change_data.
    DATA(lo_ref) = get_reference( ).

    LOOP AT lo_ref->mt_data ASSIGNING FIELD-SYMBOL(<lv_value>).
      <lv_value> = <lv_value> + 1.
    ENDLOOP.
  ENDMETHOD.

Or this:

  METHOD change_data.
    LOOP AT CAST lcl_app( get_reference( ) )->mt_data ASSIGNING FIELD-SYMBOL(<lv_value>).
      <lv_value> = <lv_value> + 1.
    ENDLOOP.
  ENDMETHOD.

Everything will be OK