Constructor Expressions

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Most ABAP statements do one thing and leave the result in a variable you declared earlier. A constructor expression is different: it is a small piece of code that produces a value right where you write it, so you can pass the value straight to a method, assign it to a variable or use it inside a larger expression. A newcomer meets them in almost every modern ABAP program, because they replace several lines of declare, fill and append with a single line. This page explains each constructor expression, how ABAP works out the type of the result, and how to build a table of claim items and add up their amounts. It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). All the expressions below are available in ABAP Cloud and in classic, Standard ABAP; the examples are plain ABAP that applies on premise and in the Public Edition alike.

Before you read

Key terms

  • Constructor expression: an expression that starts with an operator such as VALUE or COND, ends with a closing parenthesis and creates a value.

  • Operand type: the data type the constructor expression must produce, either written after the operator or taken from the place where the expression is used.

  • Inline declaration: a variable declared at the place where it is first written, with DATA(name) or FINAL(name), instead of in a separate DATA statement.

  • Internal table: a table that lives only in the memory of the running program and holds any number of rows of the same type.

  • Iteration expression: the FOR part of a constructor expression that repeats once per row or per counter value.

  • Data reference: a pointer to a data object, created with REF.

The shape of a constructor expression

Every constructor expression has the same shape: an operator name, the type of the result, and the arguments in parentheses. The type may be written out, as in VALUE ty_items( ... ), or replaced by the hash sign #, which tells ABAP to take the type from the place where the expression is used. The # form works only where the data type required at that position is unique and completely known when the program is compiled, for example when the expression is assigned to a variable that already exists. When you declare the variable in the same statement with DATA(name) = and use VALUE, there is no required type to take, so you write the type name instead. A few operators have their own rule: with REDUCE, for example, the type of the first variable declared after INIT is used.

The operators fall into three groups, shown in the diagram below.

flowchart LR CE[Constructor expression] --> A[Create or convert] CE --> B[Choose a value] CE --> C[Transform tables] A --> A1[VALUE, NEW, REF] A --> A2[CONV, EXACT, CAST] A --> A3[CORRESPONDING] B --> BX1[COND] B --> BX2[SWITCH] C --> C1[REDUCE] C --> C2[FILTER] C --> C3[FOR iterations]

Creating values: VALUE, NEW and REF

VALUE builds a structure or an internal table from the values you list. For a structure you name the components; for a table you list one row after another, each in its own pair of parentheses. Components you leave out keep their initial value. VALUE #( ) with nothing inside produces an initial value of the inferred type, which is a quick way to clear a variable. When you assign a VALUE expression to an existing variable, that variable is first set to the initial value or the start value and then filled from the parentheses. The addition BASE gives the start value: it starts from an existing table or structure and keeps its content, so the new rows are appended to it instead of replacing it.

NEW does the same job for objects and anonymous data objects: NEW zcl_claim_calc( ) creates an object and returns a reference to it, and NEW ty_item( amount = 10 ) creates an anonymous data object and returns a data reference. REF returns a data reference to an object that already exists, for example REF #( ls_item ).

The example below fills a structure and a small table of claim items with VALUE. The types are local so the code stands alone; the claim item fields follow the Expense claims running example (ZEXP_ITEM). This listing runs in the local playground once three WRITE lines are added after it: it prints TRAVEL, 4 (the number of rows after BASE) and HOTEL.

TYPES: BEGIN OF ty_item,
         claim_id TYPE c LENGTH 10,
         item_no  TYPE i,
         category TYPE c LENGTH 10,
         amount   TYPE p LENGTH 8 DECIMALS 2,
       END OF ty_item,
       ty_items TYPE STANDARD TABLE OF ty_item WITH EMPTY KEY.

DATA(first_item) = VALUE ty_item( claim_id = 'C000000001' item_no = 1 category = 'TRAVEL' amount = '120.50' ).

DATA(items) = VALUE ty_items(
  ( claim_id = 'C000000001' item_no = 1 category = 'TRAVEL' amount = '120.50' )
  ( claim_id = 'C000000001' item_no = 2 category = 'MEALS'  amount = '35.00' )
  ( claim_id = 'C000000001' item_no = 3 category = 'TRAVEL' amount = '60.00' ) ).

" BASE keeps the three rows and appends a fourth.
items = VALUE #( BASE items ( claim_id = 'C000000001' item_no = 4 category = 'HOTEL' amount = '210.00' ) ).

Converting: CONV, EXACT and CAST

CONV converts its argument to the given type using the normal ABAP conversion rules, the same ones as in an assignment. It is mostly used to get a value into the right type in the middle of an expression, and it closes the gap that VALUE leaves, because VALUE cannot build a single elementary value such as a number or a string. In CONV decfloat34( 1 / 5 ) the division is done as a decimal floating point calculation and gives 0.2, while the plain expression 1 / 5 has the type i and gives 0.

EXACT converts in the same way but checks that nothing is lost: where an ordinary conversion would silently cut a string, EXACT raises a catchable exception instead (for example cx_sy_conversion_data_loss), which you handle with TRY and CATCH.

CAST creates a reference variable of a given static type. It carries out upcasts and downcasts and replaces the older ?= operator, and CAST #( ... ) takes the target type from the place of use. A downcast, to a more specific type, is checked when the program runs, so you ask for it explicitly with CAST; an upcast may use CAST but does not need to.

The first listing converts with CONV. It runs in the local playground and, with two WRITE lines added after it, prints 0 and 0,2 (the playground writes the decimal separator as a comma).

" Without CONV the integer division gives 0; with CONV the result is 0.2.
DATA(plain) = 1 / 5.
DATA(converted) = CONV decfloat34( 1 / 5 ).

The second listing uses EXACT with a text that does not fit into three characters. It requires an SAP system; not run here.

TYPES clen3 TYPE c LENGTH 3.
DATA code TYPE clen3.

TRY.
    " EXACT raises an exception when the text does not fit the target type.
    code = EXACT clen3( 'TRAVEL-EXPENSES' ).
  CATCH cx_sy_conversion_data_loss.
    code = 'TRV'.
ENDTRY.

Copying between structures and tables: CORRESPONDING

CORRESPONDING creates a structure or table by assigning the components that have the same name in the source and the target, or that a mapping rule pairs up. Three additions adjust this. MAPPING assigns a source component to a target component with a different name, written MAPPING target = source. EXCEPT names components that get no content; they stay initial. BASE ( base ), with its own pair of parentheses, keeps the original values of base. For nested structures and tables the addition DEEP also matches the lower levels. The example below runs in the local playground and, with two WRITE lines added after it, prints C000000001 and 425,50.

TYPES: BEGIN OF ty_claim_view,
         claim_id TYPE c LENGTH 10,
         total    TYPE p LENGTH 8 DECIMALS 2,
       END OF ty_claim_view,
       BEGIN OF ty_claim_row,
         claim_id TYPE c LENGTH 10,
         sum      TYPE p LENGTH 8 DECIMALS 2,
         status   TYPE c LENGTH 1,
       END OF ty_claim_row.

DATA(row) = VALUE ty_claim_row( claim_id = 'C000000001' sum = '425.50' status = 'S' ).

" Same-name components are copied; sum goes to total through MAPPING; status has no partner and is ignored.
DATA(view) = CORRESPONDING ty_claim_view( row MAPPING total = sum ).

Choosing a value: COND and SWITCH

COND evaluates logical expressions one after another and returns the value of the first branch that is true. The last branch can be an ELSE; without it, the result is the initial value when no condition holds. SWITCH is the shorter form for the common case of comparing one operand with several constants: it picks the value that goes with the matching WHEN, and falls back to ELSE. Both can be used with # when the result goes to a variable of a known type, and both can declare local helper variables with LET, which are visible only inside the expression. The example below runs in the local playground and, with two WRITE lines added after it, prints Approved and Manager.

DATA claim_status TYPE c LENGTH 1 VALUE 'A'.
DATA total        TYPE p LENGTH 8 DECIMALS 2 VALUE '425.50'.

DATA(status_text) = SWITCH string( claim_status
                      WHEN 'D' THEN `Draft`
                      WHEN 'S' THEN `Submitted`
                      WHEN 'A' THEN `Approved`
                      ELSE `Unknown` ).

DATA(approval_level) = COND string(
                         WHEN total > 1000 THEN `Director`
                         WHEN total > 250  THEN `Manager`
                         ELSE `Automatic` ).

Repeating: FOR iterations

The FOR expression, called an iteration expression, can be used inside VALUE, NEW and REDUCE. It sits inside the parentheses and repeats once per pass, and the expression to its right is evaluated every time. There are two kinds.

  • A table iteration, FOR wa IN itab, visits the rows of itab the way LOOP AT does; wa is a work area that exists only inside the expression. Add WHERE ( ... ) after the table to visit only some rows, or INDEX INTO idx to also get the row number as a variable of type i.

  • A conditional iteration, FOR i = 1 UNTIL i > 5 or FOR i = 1 WHILE i <= 5, behaves like a DO or WHILE loop. With UNTIL the condition is checked after each pass, so there is at least one pass; with WHILE it is checked before each pass. A numeric counter goes up by 1 on every pass; for other types, or another step, you write THEN expression.

  • FOR GROUPS loops over the groups that GROUP BY builds; grouping is explained with the loops of internal tables.

Inside VALUE, a FOR creates one row per pass, so VALUE ty_items( FOR i = 1 UNTIL i > 3 ( ... ) ) builds a table of three rows. Several FOR parts in a row work like nested loops. The variables a FOR creates (wa, i) are local to the expression and cannot be used after it. The system field sy-index is not set by a FOR expression.

Totalling and filtering: REDUCE and FILTER

REDUCE collapses a series of values into a single result, the way a running total works. It has three parts. INIT declares one or more result variables with their starting values; one or more FOR parts say what to repeat over; NEXT says how the variables change on every pass. After the last pass the expression returns the value of the first INIT variable.

FILTER builds a new table from an existing one, keeping only the rows that meet a condition. The condition is a WHERE on components of a table key, so the source table needs a sorted key or a hash key; if its primary key is not one, a secondary key must be available and chosen with USING KEY. Several comparisons can be joined with AND only, and with a hash key only = is allowed. EXCEPT turns the filter around and keeps the rows that do not match. With # the type of the source table is used as the type of the result. The official documentation notes that FILTER is more efficient than the same filtering written with FOR.

Worked example: claim items and their total

The example builds the items of one claim with VALUE and FOR, totals them with REDUCE, and then sums only the travel items with a second REDUCE that carries a WHERE. The amounts are generated from a small list of categories, a stand-in for the rows a real program would read from ZEXP_ITEM. This listing runs in the local playground and, with three WRITE lines added after it for total, travel_total and the number of items, prints 425,50, 180,50 and 4 (the playground writes the decimal separator as a comma).

TYPES: BEGIN OF ty_item,
         claim_id TYPE c LENGTH 10,
         item_no  TYPE i,
         category TYPE c LENGTH 10,
         amount   TYPE p LENGTH 8 DECIMALS 2,
       END OF ty_item,
       ty_items TYPE STANDARD TABLE OF ty_item WITH EMPTY KEY.

TYPES: BEGIN OF ty_receipt,
         category TYPE c LENGTH 10,
         amount   TYPE p LENGTH 8 DECIMALS 2,
       END OF ty_receipt,
       ty_receipts TYPE STANDARD TABLE OF ty_receipt WITH EMPTY KEY.

DATA(receipts) = VALUE ty_receipts(
  ( category = 'TRAVEL' amount = '120.50' )
  ( category = 'MEALS'  amount = '35.00' )
  ( category = 'TRAVEL' amount = '60.00' )
  ( category = 'HOTEL'  amount = '210.00' ) ).

" One claim item per receipt; INDEX INTO supplies the item number.
DATA(items) = VALUE ty_items(
  FOR receipt IN receipts INDEX INTO idx
  ( claim_id = 'C000000001'
    item_no  = idx
    category = receipt-category
    amount   = receipt-amount ) ).

" Add up every item amount.
DATA(total) = REDUCE ty_item-amount(
  INIT sum = CONV ty_item-amount( 0 )
  FOR item IN items
  NEXT sum = sum + item-amount ).

" Add up only the travel items.
DATA(travel_total) = REDUCE ty_item-amount(
  INIT sum = CONV ty_item-amount( 0 )
  FOR item IN items WHERE ( category = 'TRAVEL' )
  NEXT sum = sum + item-amount ).

" total is 425.50 and travel_total is 180.50.

The INIT value is converted with CONV so that the sum has two decimal places from the first pass; an untyped 0 would make the variable an integer and the cents would be lost. The same total could be built with a LOOP AT and a DATA statement for the running sum, and for long or branching bodies the loop is easier to read. A REDUCE is at its best when the body is one short formula.

The next listing keeps only the rows of a table that match a key condition. The table has a sorted key on the category so that FILTER can use it. This listing runs in the local playground and, with a WRITE of the number of rows and a loop that writes each item_no, prints 2, then 2 and 3.

TYPES: BEGIN OF ty_item,
         item_no  TYPE i,
         category TYPE c LENGTH 10,
         amount   TYPE p LENGTH 8 DECIMALS 2,
       END OF ty_item,
       ty_items TYPE SORTED TABLE OF ty_item WITH NON-UNIQUE KEY category.

DATA(items) = VALUE ty_items(
  ( item_no = 1 category = 'MEALS'  amount = '35.00' )
  ( item_no = 2 category = 'TRAVEL' amount = '120.50' )
  ( item_no = 3 category = 'TRAVEL' amount = '60.00' ) ).

" Only the rows whose category equals TRAVEL; the table has a sorted key on category.
DATA(travel_items) = FILTER #( items WHERE category = 'TRAVEL' ).

Older material you may meet

Code and books written before release 7.40 do not use constructor expressions, and many programs in a maintained system still look that way. Instead of DATA(items) = VALUE ty_items( ... ) you will see a DATA statement, a CLEAR, and one APPEND or INSERT per row, with a work area filled component by component. A running total is a DATA variable that a LOOP AT adds to; a conditional value is an IF block assigning to a helper variable; a type change goes through an auxiliary variable instead of CONV; and moving fields with matching names is the statement MOVE-CORRESPONDING. Reading such code does not need a translation first, because each form does the same job as its constructor expression. In the code you write or change, prefer constructor expressions and inline declarations, which is why this page teaches them first. Do not rewrite working old code only to change its style.

Summary

  • A constructor expression produces a value in place: VALUE builds structures and tables, NEW and REF produce references, and CONV, EXACT and CAST change types.

  • The # sign takes the result type from the place of use; write the type name when there is nothing to infer from.

  • CORRESPONDING copies same-named components, with MAPPING, EXCEPT and BASE to adjust it; COND and SWITCH choose a value without an IF block.

  • FOR repeats an expression over rows or counters, REDUCE collapses the repeated values into one result, and FILTER keeps the rows of a table with a suitable key that meet a condition.

  • Older code uses DATA, APPEND, LOOP AT and MOVE-CORRESPONDING for the same jobs.

Try it

To do this by hand, follow the guide Work with Internal Tables: it builds claim items with VALUE, reads them with table expressions, sorts, groups and totals them.