The treat expression, like the typeswitch expression, is used to assure the processor that only values of a certain type will participate in a particular function or operation. The syntax of a treat expression is shown in Figure 14-2.
Building on the ProductType
/HatType
example from the previous section, suppose you would like to display the size of a product, if it is a hat. Although ProductType
doesn't allow a size
child, HatType
does. You could use the query shown in Example 14-4.
Example 14-4. A query without a treat expression
if ($myProduct instance of element(*,prod:HatType)) then <p>The size is: {data($myProduct/size)}</p> else ( )
It tests to see if the product is a hat, and if it is, constructs a p
element that contains its size. Unfortunately, an implementation that supports static typing will raise a type error with this query. This is because, as far as the processor knows, $myProduct
has type ProductType
, which does not allow a size
child. As discussed in the previous section, it does not matter that you check the type of $myProduct
in the enclosing if expression.
Example 14-5 shows a revised query that uses a treat expression to assure the processor that $myProduct
is indeed an element of type HatType
.
Example 14-5. A query with a treat expression
if ($myProduct instance of element(*,prod:HatType)) then <p>The size is: {data(($myProduct treat as element(*,prod:HatType))/size)}</p> else ( )
Unlike a cast expression or a type constructor, the treat expression does not actually change the type of $myProduct
. It doesn't need to, because the type of $myProduct
should already be prod:HatType
or some matching type. Like other static-typing-related expressions, it simply postpones any errors to runtime by saying, "I know that all the values are going to be valid HatType
values, so don't raise an error during the analysis phase."
If it turns out later during the evaluation phase that there is a $myProduct
value that does not match HatType
, the error is raised at that time. The rules of sequence type matching are used to determine whether the value matches. In this particular example, it will never raise this error because it checks the type of $myProduct
before evaluating the /size
path.
If you're familiar with casts in Java or C#, you'll recognize that most casts in those languages are assertions (like treat as
) rather than actual type conversions. XQuery uses cast as
to mean a type conversion, and treat as
to mean a type assertion.
3.137.183.210