Application Development Blog Posts
Learn and share on deeper, cross technology development topics such as integration and connectivity, automation, cloud extensibility, developing at scale, and security.
cancel
Showing results for 
Search instead for 
Did you mean: 
AndreaUS
Product and Topic Expert
Product and Topic Expert
6,884

ABAP CDS has released a new killer feature: CDS enumerated types. CDS enumerated types make enumerations globally available and reusable in different contexts.

Enumerations define a fixed set of values, and objects typed with an enumerated type can have only one of the predefined values. So enumerations contribute to type safety and data consistency. Enumerations were first introduced in the ABAP programming language with ABAP release 7.51. For details, see horst.keller's  blog post ABAP News for Release 7.51 – Enumerations | SAP Blogs. 0281bd377f70426e8bb9d2d0005e7762 also explains various enumeration techniques, such as enumerations as constants in interfaces, DDIC domains with fixed values, and OO enumerations Enumerations in ABAP | SAP Blogs.
This blog post explains the new ABAP CDS enumerations.

Release info

    • 2308 SAP BTP ABAP Environment
    • ABAP Release 7.58
    • SAP S/4HANA 2023

Creating a CDS enumerated type

In ADT, an enumerated type is created as a repository object of the type Type. 

A template for enumerated types is also available.

Syntax

A CDS enumerated type is defined in the ABAP development tools for Eclipse (ADT) as a CDS type definition with the following syntax:

Explanation

  • The CDS enumerated type can have header annotations that add domain-specific logic.
  • The name of the CDS enumerated type EnumType is defined after the DEFINE TYPE.
  • Defining a base type BaseType is mandatory. The following data types are possible as base type: INT1, INT2, INT4, CHAR with length 1 to 8, NUMC with length 1 to 8.
  • Enumerated constants and enumerated values are defined in a list in curly brackets.
  • You can add text labels and headings to the enumerated constants. This allow you to define longer, more user-friendly names for user interfaces.
  • Exactly one of the enumerated constants must have the enumerated value INITIAL. It generates the initial value of the base type.

Example

Definition of an enumerated type DEMO_CDS_ENUM_WEEKDAY. The base type is abap.int1 and the enumerated values of the enumerated constants MON, TUE, ... are 0 to 6.

@EndUserText.label: 'Days of the week' 
define type DEMO_CDS_ENUM_WEEKDAY : abap.int1 enum 
{ 
  @EndUserText.label: 'Monday' 
  MON = initial;
  @EndUserText.label: 'Tuesday' 
  TUE =       1; 
  @EndUserText.label: 'Wednesday' 
  WED =       2; 
  @EndUserText.label: 'Thursday' 
  THU =       3; 
  @EndUserText.label: 'Friday' 
  FRI =       4; 
  @EndUserText.label: 'Saturday' 
  SAT =       5; 
  @EndUserText.label: 'Sunday, bloody Sunday' 
  SUN =       6; 
} 

In ABAP, an equivalent enumerated type can be defined as follows:

"ABAP enumerated type with enumerated structure
    TYPES:
      BEGIN OF ENUM abap_wd STRUCTURE abap_wd BASE TYPE int1,
        mon,
        tue,
        wed,
        thu,
        fri,
        sat,
        sun,
      END OF ENUM abap_wd STRUCTURE abap_wd.

But please note that you of course cannot make assignments between the two enumerated types, because an enumerated type is compatible only with itself.

Differences between ABAP enums and CDS enums

    • In ABAP, the base type is optional. If no base type is specified, the default is i.
    • In ABAP, the enumerated values are optional. If no values are specified, the enumerated constants are numbered implicitly, starting from 0.
    • A CDS enumerated type behaves like an enumerated structure in ABAP. This means that a CDS enumerated type is always addressed by its name plus the name of an enumerated constant, for example: EnumName-EnumConstant in ABAP and EnumName.#EnumConstant in ABAP CDS.

Domains with fixed values and CDS enums

In ABAP Dictionary, you can define domains with fixed values. The fixed values are a set of allowed values, similar to the enumerated constants. However, the domain fixed values are evaluated for the input help of dynpro fields. CDS enumerated types make enumerations globally available and reusable in different contexts. CDS enumerated types are intended to replace domains with fixed values.

Using CDS enumerated types

CDS enumerated types can be used as follows:

  • In ABAP CDS for typing and casting, as operands in expressions, and in comparisons.
  • In ABAP for typing after the TYPES statement.
  • In ABAP SQL as elementary operands and in cast expressions.

Using CDS enumerated types in ABAP

The enumerated type can be used for declaring an enumerated variable wd in an ABAP program. By doing so, an enumerated structure named demo_cds_enum_weekday is implicitly declared in the current context and can be used there. wd initially contains the content of the initial enumerated constant demo_cds_enum_weekday-mon.

DATA wd TYPE demo_cds_enum_weekday. 
ASSERT wd = demo_cds_enum_weekday-mon. 
cl_demo_output=>display( demo_cds_enum_weekday ).  

The result looks as follows:

Using CDS enumerated types in ABAP CDS

The CDS enumerated type can be used in CDS entities for typing of elements or parameters, as operands in expressions, and in comparisons.

Here’s an example:

@EndUserText.label: 'Cast to enum'
@AccessControl.authorizationCheck: #NOT_REQUIRED
define view entity demo_cds_enum1
  with parameters
    p_weekday :DEMO_CDS_ENUM_WEEKDAY
  as select from DEMO_CDS_ENUM_2
{
  key id,
      int1,
      cast(int1 as DEMO_CDS_ENUM_WEEKDAY) as weekday1,
      DEMO_CDS_ENUM_CHAR.#first_value     as EnumConstant
}
where
  weekday = $parameters.p_weekday

The elements weekday and EnumConstant both have the data type ENUM. You can see this in the debugger and in the code element information in ADT.

Using CDS enumerated types in ABAP SQL

In ABAP SQL, CDS enumerated constants can be used in operand positions such as the WHERE clause and the ORDER BY clause. The enumerated constants of a CDS enumerated type can be accessed with a component selector: EnumName-EnumConstant.
The following code snippet demonstrates accessing the CDS view entity using ABAP SQL. It first inserts data into the database table DEMO_DDIC_TYPES and then it selects all elements from the CDS view entity. The columns weekday and EnumConstant of the inline declared table result both have an enumerated type.
Note: If the field INT1 contains a value that is not contained in the list of enumerated values of the CDS enumerated type DEMO_CDS_ENUM_WEEKDAY, a runtime error occurs.

*fill database table
DELETE FROM demo_ddic_types.
INSERT demo_ddic_types FROM TABLE @( VALUE #(
 ( id = 'A' int1 = 1 )
 ( id = 'B' int1 = 6 )
*( id = 'C' int1 = 7 )   -> runtime error because 7 is not an allowed value
) ).
*SELECT from cds view entity
SELECT *
FROM demo_cds_enum_2
INTO TABLE @DATA(result)
WHERE EnumConstant = @demo_cds_enum_char-first_value.
*display result
cl_demo_output=>display( result ).

The result looks as follows:

The following screenshot shows the debugger view of the variable result. You can see that the columns Weekday and EnumConstant of the result table declared inline both have an enumerated type.

Outlook

It is currently not possible to define database tables with enumerated fields. The ENUM data type is not available for typing in ABAP Dictionary. However, the ABAP CDS team is currently preparing a new CDS entity as a successor to DDIC database tables, called CDS table entity. The fields of CDS table entities can have the data type ENUM.

Official documentation

Happy Coding!

18 Comments
Sandra_Rossi
Active Contributor
ABAP 7.58 wow! The latest ABAP documentation seems to be still 7.57. Is it a preview blog post before official release? When should 7.58 (doc) be available? Thanks.
AndreaUS
Product and Topic Expert
Product and Topic Expert
This feature has been released with 7.93, 2308. RTC is today. It will perhaps be included in the next on-prem release. But yes you are right, 7.58 has not yet been released. I have removed this info from the release info. 7.58 will probably be published in October.

 
fabianlupa
Contributor

Hey aschlott ,

thanks for the mention and the details on CDS enumerations. In addition Clean ABAP also has some detailled recommendations on enumeration techniques: here and here .

One caveat of the ABAP based enumerations is no support for database fields and no labels for the UI, so you kind of also always have to define a data element and a domain with (redundantly maintained) fixed values and use the base type addition to connect them. The new CDS based enumerations seem to now support labels using the annotation. However, database fields still have to wait until CDS table entitys, if I understand it correctly?

Also how will domains with fixed values compare to CDS enumerations in the future? Since CDS enums seem to directly define a type the reuse of a single domain (weekday) in multiple data elements (e.g. first_day_of_week) does not seem to be possible. Can you differentiate the use cases of both technologies and clarify the strategy going forward? Will there be some kind of native integration between domains / data elements and ABAP / CDS enumerations or will one technology replace the other?

Best regards

Fabian

AndreaUS
Product and Topic Expert
Product and Topic Expert

Hi Fabian,

yes, you can define UI labels for CDS-based enumerations using annotations. And yes, database fields still have to wait until CDS table entities.

Regarding reuse: With CDS enumerations, reuse is possible. You can create type hierarchies, that means, you can type an enumerated type with another enumerated type. In this way, you can reuse an enum type in another enum type and build type stacks. Here's an example:

@EndUserText.label: 'CDS enum typed with another enum' 
define type DEMO_CDS_ENUM_STACK: DEMO_CDS_ENUM_WEEKDAY

F2 shows that the definition from the base type is inherited

CDS enumerated types combine domains and data elements, and there is currently no integration between the two concepts. Migration support may be offered in the future, but this is still under discussion. So for now, DDIC domains+ data elements and CDS enums are two separate technologies.

In general, the ABAP Cloud strategy is to use CDS for data modeling instead of ABAP Dictionary. ABAP Dictionary data types can still be used, but for new developments, it is recommended to use CDS means instead whenever possible.

Does that help?

fabianlupa
Contributor
0 Kudos
Yes! Thanks for the clarifications.
fabianlupa
Contributor

Do I dare to ask again... Will you maybe be providing a released CDS enumerated type in SAP_BASIS for ..... boolean values?

@EndUserText.label: 'Boolean Value' 
define type BOOL : abap_boolean enum
{
@EndUserText.label: 'False'
FALSE = initial;
@EndUserText.label: 'True'
TRUE = 'X';
}

If I understand correctly that would allow for compile time checks for the new-ish abap_boolean domain with only 2 values.

METHODS shutdown_reactor IMPORTING skip_cooldown_procedure TYPE bool.

shutdown_reactor( bool-true ).
shutdown_reactor( bool-false ).

shutdown_reactor( CONV #( abap_true ) ).
shutdown_reactor( CONV #( abap_false ) ).

shutdown_reactor( ' ' ). " syntax error
shutdown_reactor( '-' ). " syntax error
shutdown_reactor( 'x' ). " syntax error
shutdown_reactor( abap_undefined ). " syntax error
shutdown_reactor( abap_true ). " syntax error
shutdown_reactor( CONV #( abap_undefined ) ). " runtime error

 

Preferably not named something like xsdbool_enum 😉

AndreaUS
Product and Topic Expert
Product and Topic Expert

Hi 0281bd377f70426e8bb9d2d0005e7762,

not that simple. Boolean types can have two values or three values and there are already many custom Boolean types implemented as data elements or structures, so its not that easy to find a free name. But you are right, it would be very handy and it is under discussion. 

Best

Andrea

AndreM
Explorer
0 Kudos
Are there any thoughts on removing at least some of the base-type limits? It feels very strange to find such a cool feature being limited to (more or less) only integer values. Why not Class-Names or other strings? Why not object- or data-references? Why not structures? I could imagine a whole lot of useful things to do with enums apart from weekdays and other constants that can be easily mapped to an integer.

That said: cool feature this is!
AndreaUS
Product and Topic Expert
Product and Topic Expert
0 Kudos
Thanks for your suggestion. Sounds interesting.

The current CDS enums have the main use case to limit the values that can be assigned to an object. The base type is is almost irrelevant and does not play a role when enumerated objects are used.

As the successor of data elements and domains with fixed values, the CDS team has analyzed the most frequently used data types of domains with fixed values and used them as the basis for their design. The base types of the CDS enums cover the most commonly used types of domains with fixed values.

Another CDS type is currently under discussion. This type might allow defining lists of fixed values with a broader range of data types, and there will be less strict checks than the current CDS enums. That might cover some of your use cases.

What would be a use case of enums with data-references? Or enums with class names? Does any other programming language have this kind of enums?
fabianlupa
Contributor
0 Kudos
Or enums with class names? Does any other programming language have this kind of enums?

For many including me the non-object-oriented implementation of enumerations in ABAP was quite unusual. See the blog you linked in chapter "Class based enumerations" for an example in Java. Enumerations in ABAP | SAP Blogs

ABAP needs a wrapper class with some boilerplate code to be able to also provide operations for enum values, or even additional attributes -> enum instances.

Maybe that's what andre.muehlnikel1 was hinting at.
fabianlupa
Contributor
Some day the advanced technique of a boolean data type with two values, no more, no less, will find its way to ABAP 😉
AndreaUS
Product and Topic Expert
Product and Topic Expert
0 Kudos
🤣
AndreaUS
Product and Topic Expert
Product and Topic Expert
Yes indeed, ABAP-defined enums need a "namespace" for the values if you want to make them globally available. A global class / interface can be used for this purpose. With CDS enums, it is now the globally unique DDIC name that provides the namespace.

Java is OO-centric and ABAP is not. Java has a completely different type concept than ABAP and I'm not sure if comparing both languages in this regard is useful. One of the strengths/characteristics of ABAP are the types embedded in the language with the resulting type safety of the compiler.

What would be the additional benefit of OO-based enums in ABAP? Is there anything that cannot be covered by CDS enums?
fabianlupa
Contributor
0 Kudos

I agree, the tightly integrated type system with compile time safety is one of the strong points of ABAP, especially combined with the ABAP Dictionary and now CDS.

As for OO-based enums you could extend your day of week example like this:

public enum DayOfWeek {
MONDAY(true),
TUESDAY(true),
WEDNESDAY(true),
THURSDAY(true),
FRIDAY(true),
SATURDAY(false),
SUNDAY(false),

private final boolean workDay;

private constructor(boolean workDay) {
this.workDay = workDay;
}

public DayOfWeek nextDay() {
return switch(this) {
case MONDAY -> TUESDAY;
case TUESDAY -> WEDNESDAY;
case WEDNESDAY -> THURSDAY;
case THURSDAY -> FRIDAY;
case FRIDAY -> SATURDAY;
case SATURDAY -> SUNDAY;
case SUNDAY -> MONDAY;
};
}

public boolean isWorkDay() {
return workDay;
}

public DayOfWeek nextWorkDay() {
DayOfWeek result = nextDay();
while (!result.isWorkDay())
result = result.nextDay();
return result;
}

public DayOfWeek nextDayOff() {
DayOfWeek result = nextDay();
while (result.isWorkDay())
result = result.nextDay();
return result;
}
}

DayOfWeek someDay = DayOfWeek.MONDAY;
DayOfWeek nextDayOff = someDay.nextDayOff();

 

While in ABAP as they are not natively integrated with ABAP Objects you'd have to "manually wire things up" in a enumeration class with a class_constructor etc. or provide the functionality as for example static methods in a helper class.

Of course the CDS based enums would probably allow for or at least go in the direction of putting this logic in the database layer, which is the strategically correct choice. So for the most part it just takes a bit of getting used to (for me).

I'd be curious how you would design this additional functionality in ABAP/CDS. When CDS enums are supported on the database using CDS Table Entities this would probably be just a database table with the enum as a key field with a CDS entity on top with associations and maybe table functions for the loops?

AndreaUS
Product and Topic Expert
Product and Topic Expert

Objects in ABAP come exclusively as references, that is, behind a type
REF TO Class. There are no "inline objects" in ABAP.

SAP tried to find the easiest, most migration-friendly, and most performant way from ABAP-simulated enums (which are classically structured constants) to type-safe enums. 

From the ABAP language point of view, CDS enums are a new way to define global enums in CDS instead of in classes or interfaces. What is really new here is that constants, not just types, are defined, for which ABAP generates data objects at runtime. Moreover, ABAP SQL can now also handle enums. Seen from above, ABAP with its type world can handle all the ingredients of modeling, because that's what it's made for.

Moreover, with CDS enums, data consistency can be ensured at DB-level. As soon as CDS table entities with ENUMs are available, corresponding DB-constraints in HANA will ensure that only allowed values are written.

Hope this makes sense to you.

PS this is the aggregated knowledge of some ABAP experts, I'm not that knowledgeable (yet 😋)

petr_kobza
Advisor
Advisor
Hello colleagues, when defining a CDS field with CDS enums, will I get the Value Help for free?
AndreaUS
Product and Topic Expert
Product and Topic Expert

Hi Petr,

for classical SAP GUI value help, this is not planned.

In OData services created using RAP, CDS enums are not supported yet. In the future, it is planned to support CDS enums in SADL and OData and the value help will work out-of-the-box, without any special enablement. However, there is no fixed date for that and it is not part of the official roadmap.

In analytical scenarios evaluated by the ABAP Analytical Engine, parameters of type ENUM get the value help for free.

 

petr_kobza
Advisor
Advisor
Labels in this area