A continued annoyance in ABAP is that one is unable to distinguish a variable that was never set from one that was set to the initial value for its data type, and that failing accesses to internal tables via itab[...]
expressions throw CX_SY_ITAB_LINE_NOT_FOUND
which is costly in terms of runtime to deal with.
For enumerated types, one can define the first variant as invalid
to guard against the first confusion:
TYPES:
BEGIN OF ENUM my_bool,
invalid,
true,
false,
END OF ENUM my_bool.
(Do not actually use this type as an ABAP_BOOL
replacement. The way predicative method calls behave, a method meth
returning a my_bool
would lead to obj->meth( )
inside an IF obj->meth( ).
being truthy only if it returns invalid
, since the predicative method call is equivalent to IF obj->meth( ) IS NOT INITIAL.
)
For non-enumerated types, we're out of luck. Trying to implement something like an option type to return from methods that tried and failed to access some data is blocked by the weak typing of generics:
CLASS zcl_option DEFINITION
FINAL.
PUBLIC SECTION.
CLASS-METHODS some
IMPORTING VALUE(val) TYPE any
RETURNING VALUE(option) TYPE REF TO zcl_option.
CLASS-METHODS none
RETURNING VALUE(option) TYPE REF TO zcl_option.
METHODS is_some
RETURNING VALUE(is_some) TYPE abap_bool.
METHODS get
RETURNING VALUE(val) TYPE ???.
ENDCLASS.
where trying to use a generic type in the return value of get
fails with "returning parameters must be fully typed".
Is there a way I can construct something like the option type in ABAP, or even more generally sum types?