Search code examples
inlinedeclarationabapvariable-types

Type determination in inline declared vars?


When we declare a variable normally we specify its type.

What happens to the type of an inline declaration variable if we don't specify it? Is it assigned according to the value it receives?

For example:

Ex.1 Here we get the string type by the value we pass in?

DATA(lv_name) = 'Testing Value'.

Ex.2 Here we get lt_mara as TYPE TABLE OF mara?

SELECT * FROM mara 
         INTO TABLE @DATA(lt_mara) UP TO 10 ROWS.

Do I understand this issue correctly?


Solution

  • Yes, the type gets derived automatically at activation depending on the type of what you assign. DATA(lv_name) = 'Testing Value' will result in a TYPE c LENGTH 13, because that's the length of the character literal you assign. If you want a TYPE string, assign it with the string template syntax: DATA(lv_name) = |Testing Value| .

    If you want to force a specific type, then you can combine it with the CONV operator. This is most useful with numeric types, because there are no dedicated literals for any of them except for TYPE i. For example:

    DATA(lv_num) = CONV decfloat16( '12.5' ).
    

    This will result in a TYPE decfloat16 variable with the value of 12.5.

    There is a slight peculiarity with TYPE p LENGTH x DECIMALS y types. For example, this does not work:

    DATA(lv_num) = CONV p LENGTH 10 DECIMALS 2( '12.5' ). "<- Syntax error!
    

    But you can use the CONV-operator with TYPE p if you define a named type beforehand:

    TYPES type_my_decimal TYPE p LENGTH 10 DECIMALS 2.
    DATA(lv_num) = CONV type_my_decimal( '12.5' ). 
    

    (This does of course work just as well with dictionary types).

    When you use an inline declaration in a SELECT * FROM mara, then the resulting structure won't technically be the dictionary-type MARA, but a type which has the exact same columns as MARA. So it is identical for most intents and purposes. Inline declarations with SELECT are most useful when you do not do just a SELECT * but when you specify a list of fields you want. Using an inline declaration means that you do not need to define a custom data-structure which you would then need to manually keep in sync whenever you change the column list of your SELECT .