Casts

Casting allows transforming data from one type to another. Each section on types describes the casts allowed for that data type.

CAST

Any expression can be casted at runtime to another type, causing a runtime error if casting is not allowed.

Syntax:

CAST(<expression> AS <type>)

For example:

v: any := 1;

CAST(v AS INT) // 1
CAST(v AS INTERVAL) // Runtime error!

TRY_CAST

Similar to CAST, but returns null if casting is not allowed.

Syntax:

TRY_CAST(<expression> AS <type>)

For example:

v: any := 1;
TRY_CAST(v AS double) // 1.0
TRY_CAST(v AS interval) // interval "1 day"

TRY_CAST(v AS time) // null

Casting complex data structures

Both CAST and TRY_CAST can be used to cast the complex data structures. These castings are allowed as long as the casting is structurally compatible: i.e. records have the same field names, collections are casted to collections, and the inner types are castable to each other.

For example:

a := [(name: "Miguel", age: "39")]
CAST(a AS COLLECTION(RECORD(name: string, age: int)))   // [(name: "Miguel", age: 39)]