Apama 10.3.1 | Apama Documentation | Developing Apama Applications | Developing Apama Applications in EPL | Defining What Happens When Matching Events Are Found | Defining conditional logic with the ifpresent statement
 
Defining conditional logic with the ifpresent statement
The ifpresent statement is used to check if one or more values are empty (that is, whether they have a value or not). It unpacks the values into new local variables and conditionally executes a block of code.
The ifpresent statement is followed by one or more expressions with an optional name of a target variable followed by a block of code. If each expression is not empty, then the value of the expression is placed in a new local variable whose name is supplied after the keyword as. If the expression is a simple identifier (that is, it is referring to a variable or parameter), then the as identifier part can be omitted; a new local variable (which shadows the original variable) is created with the same name. Multiple expressions can be used in a single ifpresent statement, separated by commas.
If all the expressions have non-empty values, then the first block is executed. A block consists of one or more statements enclosed in curly braces, { }. The new local variables are only available in the first block of the ifpresent statement, where they are guaranteed to have non-empty values.
ifpresent can be optionally followed by an else keyword and block, which is executed if any of the supplied expressions do not have a value.
For optional types, the new local variable is of the unpacked type (the contained type of the optional), for example:
optional<integer> possibleNumber := 42;
ifpresent possibleNumber {
// in this block, possibleNumber is of type integer,
// so we can perform arithmetic on it:
nextNumber := possibleNumber + 1;
} else {
// in practice, won't be executed as possibleNumber
// has been initialized with a value.
}
Thus, ifpresent is the recommended way of handling optional variable types. Usually, there is no need to call the getOrThrow method of the optional type. ifpresent combines the check of whether the value is empty with extracting the value and control flow, and thus reduces the amount of code that could throw an exception.
As an alternative to the ifpresent statement, you can use the getOr method of the optional type, which is less verbose than using ifpresent. This is helpful if you want to treat a missing (empty) value as having a value. For example, possibleNumber.getOr(0) will give you the number in possibleNumber, or 0 if it is empty.
ifpresent operates on expressions of the following types:
*optional
*chunk
*stream
*listener
*context
*action
*any
See the API Reference for EPL (ApamaDoc) for more information on these types.
See also The ifpresent statement.

Copyright © 2013-2019 | Software AG, Darmstadt, Germany and/or Software AG USA, Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors.