Skip to content

ABAP Keyword Documentation →  ABAP − Reference →  Program Flow Logic →  Conditional Expressions 

Conditional Operator, Type Inference

This example demonstrates a type inference for the conversion operator COND.

Other versions: 7.31 | 7.40 | 7.54

Source Code

    FIELD-SYMBOLS <fs> TYPE any.
    DATA txt TYPE c LENGTH 20.
    DATA num TYPE i.
    ASSIGN num TO <fs>.

    demo=>meth1( p = COND #( WHEN 1 = 1 THEN txt ) ).
    demo=>meth1( p = COND #( WHEN 1 = 1 THEN txt ) ).
    demo=>meth1( p = COND #( WHEN 1 = 1 THEN <fs> ) ).
    cl_demo_output=>line( ).

    demo=>meth2( p = COND #( WHEN 1 = 1 THEN txt ) ).
   "demo=>meth2( p = COND #( WHEN 1 = 1 THEN num ) ).  "not possible
   "demo=>meth2( p = COND #( WHEN 1 = 1 THEN <fs> ) ). "not possible
    cl_demo_output=>line( ).

    demo=>meth3( p = COND #( WHEN 1 = 1 THEN txt ) ).
    demo=>meth3( p = COND #( WHEN 1 = 1 THEN num ) )  ##type.
    demo=>meth3( p = COND #( WHEN 1 = 1 THEN <fs> ) ) ##type.
    cl_demo_output=>display( ).

Description

Passes constructor expressions with the conditional operator COND to differently typed formal parameters of methods. In the case of generic formal parameters, special rules apply when identifying the operand type. Replacing the conditional operator COND with SWITCH produces the same results.

  • Fully typed formal parameter
When the method meth1 is called with a fully typed formal parameter, the operand type for # is identified using this parameter and the result of the conditional expression is converted to c with length 10 in all three calls.
  • Formal parameter typed generically with c
The operand type for # is identified from the data type of the operand after THEN.
  • In the first call, the type c with length 20 of the operand after THEN matches the generic type and is used.
  • In the second call, the type i of the operand after THEN does not match the generic type and the call is not possible.
  • In the third call, no type can be derived from the generically typed field symbol <fs> after THEN. No call is possible here, since there is no inference rule for the generic type c.
  • Formal parameter typed generically with csequence
  • In the first call, the type c with length 20 of the operand after THEN matches the generic type and is used.
  • In the second call, the type i of the operand after THEN does not match the generic type and the type string is used. This is indicated by a syntax check warning.
  • In the third call, no type is derived from the generically typed field symbol <fs> after THEN and the type string is used. This is indicated by a syntax check warning.