CH03-L03 · foundation

Membership and collection size

Test whether a value is in a list and check the number of items.

General CELRuns hereDocumented
What will I learn?

You can use in and size() instead of comparing every list item manually.

Where will I try it?

Directly below, in the browser playground.

What do I do?

Run both modes, compare where their values come from, then complete the task.

Try CEL · browser pilot

Try both ways to supply values

Define local values inside one CEL expression, or provide variables as JSON input. Everything runs in your browser.

CEL pilot subset
One self-contained CEL expressioncel.bind() gives a local name to a value and returns the result of the final expression.

cel.bind()cel.bind() is an optional official extension. It is not part of the core CEL language and may not be enabled by every host application.

Tip: press Ctrl/⌘ + Enter to run.
Result

Press Run CEL to evaluate the active example.

Pilot scope: literals, explicit conversions, local cel.bind() variables, JSON variables, lists, maps, presence, collection macros, core string checks, time values, arithmetic, comparisons, logic, and the conditional operator.

What you will do

You will run the prepared expression in the playground above, change one input at a time, and explain the result. Start in CEL only, then repeat the same rule in CEL + JSON.

How it works

The in operator answers a membership question. For a list it compares the left value with each item; for a map it tests a key. size() returns the number of items. The two checks here are independent and joined with &&.

Read the prepared example

The CEL + JSON rule is:

role in allowedRoles && allowedRoles.size() == 2

Its input is:

{
  "role": "editor",
  "allowedRoles": ["editor", "admin"]
}

The CEL only tab contains the values and the rule in one expression. The enabled cel.bind() extension keeps each name local to its final argument.

Evaluation step by step

  1. role in allowedRoles is true for "editor".
  2. allowedRoles.size() == 2 is also true.
  3. The combined result is true.

Your task

  1. Run the expression.
  2. Add "viewer" to the list without changing == 2.
  3. Update the expected size to 3 and run again.

Expected observation: Adding an item makes the size check false until the expected count is updated.

Common mistake

in is not a substring operator. Use contains() when searching inside a string.

Show the explanation

It tests whether the map contains the key "editor".

Knowledge check

What does "editor" in {"editor": true} test?

Key takeaway

Use in for collection membership and size() for cardinality; keep the two meanings separate.

Sources

  • CEL-DEV — official CEL overview.
  • CEL-LANG — official CEL language definition.
  • CEL-GO-BIND — official documentation for the optional cel.bind() extension used by the self-contained tab.