ABAP Value Optional and Default value

With the new ABAP syntax, you can use the VALUE keyword to extract an entry from an internal table. So as an example, we have defined an internal table called lt_items which should be read with id = 2. So, if an entry with the component id = 2 exists, it will be transferred to ls_item as a copy by value.

DATA(ls_item) = VALUE #( lt_items[ id = 2 ] ).

" If nothing found it will produce an exception.

Now as in the code snippet above, we now have the problem, that if no entry was found, it will automatically throw an exception. If you want to handle that better, we have now the ability to add the keyword OPTIONAL inside the VALUE#( ) syntax:

DATA(ls_item) = VALUE #( lt_items[ id = 2 ] OPTIONAL ).
IF ls_item IS NOT INITIAL.
  " Do something with ls_item
ENDIF.

This method allows you to check for a value, and if nothing is found, the ls_item remains/sets to initial, which can be checked later.

Another option is to set a DEFAULT VALUE, by simply defining it instead of the OPTIONAL keyword.

DATA(ls_item) = VALUE #( lt_items[ id = 2 ] DEFAULT VALUE ( id = 0 ) ).

" ls_item is always filled with at least ( id = 0 ).

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ad blocker detected

We have detected that you are using extensions to block ads. Please support us by disabling your ad blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock