16.8.3. Nested constraints and inline casts

In some cases, you might need to access multiple properties of a nested object, as shown in the following example:

Example pattern to access multiple properties

Person( name == "mark", address.city == "london", address.country == "uk" )

You can group these property accessors to nested objects with the syntax .( <constraints> ) for more readable rules, as shown in the following example:

Example pattern with grouped constraints

Person( name == "mark", address.( city == "london", country == "uk") )

注記

The period prefix . differentiates the nested object constraints from a method call.

When you work with nested objects in patterns, you can use the syntax <type>#<subtype> to cast to a subtype and make the getters from the parent type available to the subtype. You can use either the object name or fully qualified class name, and you can cast to one or multiple subtypes, as shown in the following examples:

Example patterns with inline casting to a subtype

// Inline casting with subtype name:
Person( name == "mark", address#LongAddress.country == "uk" )

// Inline casting with fully qualified class name:
Person( name == "mark", address#org.domain.LongAddress.country == "uk" )

// Multiple inline casts:
Person( name == "mark", address#LongAddress.country#DetailedCountry.population > 10000000 )

These example patterns cast Address to LongAddress, and additionally to DetailedCountry in the last example, making the parent getters available to the subtypes in each case.

You can use the instanceof operator to infer the results of the specified type in subsequent uses of that field with the pattern, as shown in the following example:

Person( name == "mark", address instanceof LongAddress, address.country == "uk" )

If an inline cast is not possible (for example, if instanceof returns false), the evaluation is considered false.