on 2025 Jan 27 2:47 PM
I am trying to find how to access the Values from Enum in ABAP using the following example.
I have declared the following Enum
@EndUserText.label: 'Enum Value'
define type ze_testenum : abap.char(8) enum
{
UNKNOWN = initial;
Sun = '7';
Mon = '1';
Tue = '2';
Wed = '3';
Thu = '4';
Fri = '5';
Sat = '6';
}Next, I defined the following View Entity
define view entity ZI_TestEnum
as select from I_CalendarDate
{
key CalendarDate,
ze_testenum.#Sun as Word
}
where
CalendarDate = $session.system_dateThe output of the CDS is
Next, I updated the View definition to:
define view entity ZI_TestEnum
as select from I_CalendarDate
{
key CalendarDate,
ze_testenum.#Sun as Word,
cast(ze_testenum.#Sun as abap.char(8)) as Word2
}
where
CalendarDate = $session.system_dateThe output of this CDS is:
Next, I tried to use the same method in ABAP using the following class
class zcl_je_test definition
public
final
create public .
public section.
interfaces if_oo_adt_classrun.
protected section.
private section.
endclass.
class zcl_je_test implementation.
method if_oo_adt_classrun~main.
out->write( ze_testenum-mon ).
out->write( conv string( ze_testenum-mon ) ).
endmethod.
endclass.Output of this class is:
Here in ABAP, casting doesn't convert the value of Mon to 1 unlike in CDS View definition. Why this difference in behavior?
I added the following statement in the Class
out->write( conv ze_testenum( '1' ) ).Now the output of the class is
I tried the same in CDS view definition by adding the following statement
cast('2' as ze_testenum) as Word3The output of CDS now is
In summary, I am able to:
Question(1) : Is casting the correct method to access the defined fixed values (Enumerated Values) from the CDS?
Question (2): How do I convert Constant Name to Value in ABAP code?
Tagging blog owner here for better reach @AndreaUS
Request clarification before answering.
(1) yes. Use casting.
(2) CONV enum_type( dobj ). Documented here ABAP Keyword Documentation
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
For future readers: The base type must match with Enum definition
This works:
types ty_c type c length 8.
out->write( conv string( ze_testenum-mon ) ).
out->write( conv ty_c( ze_testenum-mon ) ).Output is:
MON <-- Base type doesn't match
1 <-- Base type of conversion matches with Enum defintion
| User | Count |
|---|---|
| 22 | |
| 15 | |
| 14 | |
| 5 | |
| 4 | |
| 3 | |
| 2 | |
| 2 | |
| 2 | |
| 2 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.