Documentation View

We are hiring and constantly growing! Have a look through our vacancies to find the right role for you!

ABAPMOVE_CASTING_INCLUDE - MOVE CASTING INCLUDE

ABAPMOVE_CASTING_INCLUDE - MOVE CASTING INCLUDE

PERFORM Short Reference   PERFORM Short Reference  
This documentation is copyright by SAP AG.
SAP E-Book

Effect

Casting between Reference variables (Widening Cast).

This statement is equivalent to:

o2 ?= o1.

The fields o1 and o2 must be reference variables - that is, of type REF TO. Otherwise, the system triggers the exception that can be handled MOVE_CAST_REF_ONLY . You should always perform casting if you are making an assignment between reference variables and there is no static type check during the syntax check. If a static type check does take place, you can use the normal MOVE statement or the assignment operator (=).

If the assignment is between two reference variables for which the type of the target variable can only have the same number of components as or fewer components than the source variable, then static type checks can take place. Conversely, if the assignment is between two reference variables for which the type of target variable has more components than the source variable, no type check can take place.

When you use casting, the system checks at runtime to see whether or not the reference in the source variable points to an object to which the reference in the target variable can also point. If an assignment is possible, it will take place. If not, this raises the exception that can be handled MOVE_CAST_ERROR.

Note

If the source variable is an object reference and initial, its dynamic type is handled like the empty class OBJECT, and no exception is raised.

Example

INTERFACE I1.
  DATA A.
ENDINTERFACE.

CLASS C1 DEFINITION.
  PUBLIC SECTION.
    INTERFACES I1.
ENDCLASS.

CLASS C2 DEFINITION.
  PUBLIC SECTION.
    DATA A.
ENDCLASS.

DATA: ROOT TYPE REF TO OBJECT,
      R1 TYPE REF TO I1,
      O1 TYPE REF TO C1,
      O2 TYPE REF TO C1,
      O3 TYPE REF TO C2.

CREATE OBJECT O1.

ROOT  = O1.  "Static assignment possible
ROOT ?= O1.  "Casting does the same as static assignment

CATCH SYSTEM-EXCEPTIONS MOVE_CAST_ERROR = 4.
  MOVE ROOT ?TO O2.  "Only casting possible
ENDCATCH.

IF SY-SUBRC NE 4.
  O2->I1~A = 'X'.
ENDIF.

R1  = O1.  "Static assignment possible
R1 ?= O1.  "Casting does the same as static assignment

CATCH SYSTEM-EXCEPTIONS MOVE_CAST_ERROR = 4.
  O1 ?= R1.  "Only casting possible
ENDCATCH.

IF SY-SUBRC = 0.
  WRITE / 'Casting O1 ?= R1 successful!'.
ENDIF.

CATCH SYSTEM-EXCEPTIONS MOVE_CAST_ERROR = 4.
  O3 ?= R1.  "Only casting possible
ENDCATCH.

IF SY-SUBRC = 4.
  WRITE / 'Casting O3 ?= R1 not successful!'.
ENDIF.






BAL Application Log Documentation   ABAP Short Reference  
This documentation is copyright by SAP AG.

Length: 3375 Date: 20230207 Time: 231122     sap01-206 ( 51 ms )