Skip to content
This repository has been archived by the owner on Apr 13, 2023. It is now read-only.

Latest commit

 

History

History
102 lines (79 loc) · 3.51 KB

File metadata and controls

102 lines (79 loc) · 3.51 KB
layout title_md tab unique_id author doc_root
reference12
`if` statement
documentation
docspage
Tom Bentley
../../..

#{page.title_md}

The if statement allows a block of code to be executed conditionally.

Usage

The general form of the if statement is:

if ( /* some conditions */ ) {
    /* code executed if some conditions are true */
} else if (/* other conditions */ ) {
    /* code executed if other conditions are true */
} else {
    /* code executed otherwise */
}
/* code after if statement */

There can be zero or more else if clauses, and the else clause is optional.

Description

Ceylon's if statement should already be familiar to anyone who has programmed using a C-like language.

Execution

The if condition is evaluated first, and if it is satisfied then execution proceeds with the following block of code, and after that with the code after the if statement.

Otherwise, if the if condition is not satisfied, then the first else if condition, if any, is evaluated and if that condition satisfied then its associated block is executed, followed by the code after the if statement. If the else if condition is not satisfied, then subsequent else if clauses, if any, are treated in the same way.

Finally, if none of the conditions are satisfied, the else block, if any, is executed, followed by the code after the if statement.

Conditions

The conditions in an if statement occur in condition lists.

Any expression of type Boolean may be occur in the condition list of an if statement. The if statement also supports the use of typing conditions:

These conditions narrow the type of a reference within the associated block, and in later conditions in the condition list and the rest of the control structure.

void printSqrt(Object x) {
    if (is Float x, x >= 0.0) {
        print(x^0.5);
    }
}

By not separating the operation that checks the safety of the typecast from the operation used to actually perform the typecast Ceylon eliminates the possibility that the programmer might forget to do the test before attempting the typecast, and eliminates repetition of the narrower type.

Flow typing can also affect the rest of the control structure:

void go(Car|Bicycle vehicle) {
    if (is Car vehicle) {
        // vehicle has type Car
        vehicle.drive();
    } else {
        // vehicle has type Bicycle
        vehicle.ride();
    }
}

See also