[ABAP] How do I create and use lambda functions (anonymous functions) in ABAP?

In ABAP, you can create and use lambda functions (anonymous functions) using the FUNCTION constructor.

To create a lambda function, you need to define its parameters and return type using the FUNCTION constructor. Here's an example of creating a lambda function that calculates the square of a number:

1DATA(lv_lambda_function) = NEW abap_funcdescr( ).
2lv_lambda_function->parameters = VALUE #(
3  ( name = 'i' kind = abap_funcdescr=>parameter_kind_input )
5lv_lambda_function->returning = NEW abap_funcdescr_returning( p_type = abap_type_numc length = 4 ).
7DATA(lv_lambda) = NEW cl_abap_lambda=>lambda(
8  funcdescr = lv_lambda_function
9  code      = |RESULT = i * i|.

In this example, we define a lambda function with a single parameter "i" of type NUMC with length 4. The code inside the lambda function multiplies the parameter "i" by itself and assigns the result to a variable "RESULT".

To use the lambda function, you can call it using the CALL method of the lambda object:

1DATA(lv_result) = lv_lambda->call( i = '5' ).
2WRITE lv_result.

In this example, we call the lambda function with the parameter "i" set to '5'. The result is stored in the variable "lv_result" and then displayed using the WRITE statement.

Note that lambda functions can also have multiple parameters and return types, and you can use them in various contexts like table expressions, ABAP Unit tests, etc.