with

Syntax

	$input.with($func)

Description

Applies the function func to the entire input value input and returns the result of this function. Unlike map() or foreach(), which apply a function to each element of a set, with() applies the function to the complete result of the previous expression in the chain.

This makes it possible to use the result of a complex expression multiple times without having to break the chain or convert the expression into a block. The function func receives the entire result as an argument and can access it as required.

Parameters

parameter name Type Type Description Mandatory Default
Input Any The input value that is passed in full to the function. This is typically the result of the previous expression in a method chain. yes
func Function The function that is to be applied to the entire input value. This function receives a parameter (the input value) and can use it multiple times. yes

Return value

Type: Any

The result of the evaluation of the function func. The return type depends on what the func function returns.

Examples

Calculation of statistics on a list

	list(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30)
  .filter(x -> $x > 5)
  .with(largeNumbers -> {
    "count": $largeNumbers.size(),
    "sum": $largeNumbers.sum(),
    "average": $largeNumbers.sum() / $largeNumbers.size(),
    "min": $largeNumbers.min(),
    "max": $largeNumbers.max(),
    "doubled": $largeNumbers.map(x -> $x * 2)
  })

Output: An object with the calculated statistics: {count=9.0, sum=130.0, average=14.444444444444445, min=6.0, max=30.0, doubled=[12.0, 14.0, 16.0, 18.0, 20.0, 30.0, 40.0, 50.0, 60.0]}.

Conditional processing

	$data
  .filter(item -> $item.equals("active"))
  .with(activeItems -> 
      if($activeItems.size() > 0,
          {"status": "success", "data": $activeItems},
          {"status": "empty", "message": "Keine aktiven Einträge gefunden"}
      )
  )

Output: Depending on the result, either a success object with the active entries or a message object if no active entries were found.

Transformation with reference to the original

	$customers
  .filter(c -> $c["orders"].size() > 5)
  .with(topCustomers -> {
      "customers": $topCustomers,
      "summary": "Top-Kunden: " + $topCustomers.size() + " Kunden mit mehr als 5 Bestellungen",
      "averageOrders": $topCustomers.map(c -> $c["orders"].size()).sum() / $topCustomers.size()
  })

Output: An object containing both the filtered customer list and a summary and calculated average values based on these customers.