Search code examples
abapgeneric-programming

Single-line method calls with untyped parameters


Can I define an ABAP method where the RETURNING parameter and any IMPORTING parameters have a generic type but that can still be called in a single line as a functional method?

In other words I'd like to replace this:

CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT'
    EXPORTING
      input  = lv_external_value
    IMPORTING
      output = lv_internal_value.

With:

lv_internal_value= zcl_conversion=>alpha_input( lv_external_value ).

Unfortunately the fact that Class Methods can't have an untyped returning parameter is preventing me from declaring the functional method's return value as type ANY or CLIKE. The accepted standard of creating generic method parameters seems to be to define them as TYPE REF TO DATA and dereference/assign them. But as far as I know that prevents me from calling the method in a single statement as I have to first assign the importing parameter and then dereference the returning parameter, resulting in the same or more lines of code than a simple FM call.

Is there a way around this?


Solution

  • Unfortunately, there is no other way to dereference data than to use the dereference operator, either in the form ->* for the full value segment, or in the form ->comp, if the data object is structured and has a component named comp (and, even worse, there are a lot of places in ABAP code where you would like to use a value from a derefenced data object but can't do it for internal reasons / syntax restrictions).

    However, you could simply keep the data reference object retrieved by your method in a variable of the calling code and work with that variable (instead of using a field symbol or a variable for the derefenced value segment itself). Either generically, as a ref to data variable, or typed, using the CAST operator (new ABAP syntax).

    Most things that can be done with a field-symbol, can also be done directly with a data reference as well.

    Example: Working with a variable result of the expected return type:

    data(result) = cast t000( cl=>m( ) ).
    write result->mandt.
    

    See here the full example:

    report zz_new_syntax.
    
    class cl definition.
      public section.
        class-methods m returning value(s) type ref to data.
    endclass.
    
    start-of-selection.
      data(result) = cast t000( cl=>m( ) ).
      write: / result->mandt.  " Writes '123'.
    
    class cl implementation.
      method m.
        s = new t000( mandt = '123' ).
      endmethod.
    endclass.