You can use parse in OCL expressions to convert text into a typed value, for example when a String value must become an Integer or Decimal.
Parse a String value
parse is a type function. Call it on the target value type and pass the String that you want to convert.
| Goal | OCL expression | Result |
|---|---|---|
Convert the text '10' to a Decimal
|
Decimal.parse('10')
|
The Decimal value 10
|
Convert the text '5' to an Integer
|
Integer.parse('5')
|
The Integer value 5
|
Use the type that matches the value required by the receiving attribute or calculation. For example, use Decimal.parse when the result is used in a decimal calculation, and Integer.parse when the result must be an integer.
Handle invalid input
If the supplied String cannot be converted to the requested type, parse returns NULL. It does not return a converted fallback value.
For example, this expression returns a null value:
Decimal.parse('x')Test the result with isNull when the input can be invalid:
Decimal.parse('x').isNullThis expression returns true.
A practical pattern is to parse first and check whether the conversion succeeded before relying on the value. For example, when a user-provided String is expected to contain a decimal number, Decimal.parse(vInput) is null when vInput is not convertible to Decimal.
Scope
Most value types, including Integer and Decimal, provide parse for converting a String into a value of that type. Use this operator for text-to-value conversion. To convert a JSON string into model objects and their relationships, use JSonToObjects instead.
