Calculated expressions

What is a calculated expression?

Almost any card property with the primitive type (such as strings, numbers, and boolean expression) may refer to a calculated expression. The calculated part of the expression is written using the @{} construction and may contain variables, operators, and functions. See a list of supported functions in Embedded functions.

For example:

  • The "font_size": "@{common_text_size}" expression means the card font size property is calculated based on the common_text_size variable value.

  • To increase the font size only for certain cards relative to the same common_text_size variable, you can write the expression like this:

    "font_size": "@{sum(common_text_size, extra_size)}"
    

    This expression adds up two variables' values using the built-in sum function. The same expression can be written using the + operator:

    "font_size": "@{common_text_size + extra_size}"
    

Limitation:

You can't use expressions in card type properties or state IDs.

Syntax of calculated expressions

Calculated expressions support the following constructions:

  • Logical operators: ==, !=, !, >, >=, <, <=, &&, ||.
  • Arithmetic operators: +, -, *, /, %.
  • Ternary operator: counter > 0 ? true : 17.
  • !: operator: undefined_var !: fallback. If the expression to the left can't be calculated, the one to the right is calculated instead.
  • Grouping logical expressions: logging_enabled && (user_name == 'John' || user_email != '').
  • Function calls: mul(total_price, .83).
  • Using calculated parts within strings and string-type calculated expressions: "mail: @{'@{username}@ya.ru'}" is converted to mail: john@ya.ru.

Operator priority

Operators are evaluated in the following order of priority (from highest to lowest):

  1. !, unary - and + (logical negation, sign change)
  2. *, /, % (multiplication, division, modulo)
  3. +, - (addition, subtraction)
  4. !: (safe access/fallback operator)
  5. >, >=, <, <= (comparison)
  6. ==, != (equality, inequality)
  7. && (logical AND)
  8. || (logical OR)
  9. ? : (ternary operator)

Examples of !: operator priority

The !: operator is evaluated after arithmetic operators, but before comparison, equality, and logical operators:

@{undefined_var !: 8 + 4}          → 12     // undefined_var !: (8 + 4)
@{undefined_var !: 8 > 4}          → true   // (undefined_var !: 8) > 4
@{undefined_var !: 8 + 4 > 2}      → true   // (undefined_var !: (8 + 4)) > 2
@{undefined_var !: true || false}  → true   // (undefined_var !: true) || false

If the variable exists, its value is compared: when int_var is 1, the @{int_var !: 8 > 4} expression returns false.

Template strings

Unlike other parameters, string parameters can contain multiple calculated parts, the values of which are converted to a string and substituted in the specified places. For example:

"url": "https://marketplace.yandex.ru/profile/@{user_name}/orders/@{order_id}"

In a calculated expression, you can use template strings that contain a constant part and nested calculated expressions:

"url": "@{'https://marketplace.yandex.ru/profile/@{user_name}/orders/@{order_id}'}"

How the expression value is calculated

The calculated expression value must have the same type as the property of the card the expression is used in. This means additional conversion of data types may be required when calculating an expression.

Calculating in string parameters

Let's say the parameter value is set by the following expression: "text": "@{sum(var_a, 50)}".

First the sum function's argument values are calculated, and then the result of the function.

The first argument is a reference to a variable. To get its value, the variable is first searched in local card variables, then in a shared context for multiple cards.

Let's say var_a is an integer variable whose value is 25. The resulting number is added to the other argument, and the function result is 75. Then, in accordance with the text property context, this result is converted to a string, and the layout displays the text "75".

Serializing dictionaries and arrays to strings

When converting dictionaries and arrays to strings (for example, using the toString() function or interpolation @{dict}), JSON-like serialization is used with proper escaping of special characters:

  • Quotes " are escaped as \"
  • Backslashes \ are escaped as \\
  • Special characters: \b, \f, \n, \r, \t
  • Slashes / are escaped as \/

Example:

"text": "@{toString({'key': 'value with \"quotes\"'})}"

Result: {"key":"value with \"quotes\""}

Calculating in string parameters with strict format

The color value can be set by a string with a specific format: "text_color": "#@{str_var}".

For such parameters, the string is converted to the parameter type: the result of the calculated expression is first converted to a string and then to the parameter type.

Calculating in fields with numeric values

Numeric parameters, such as text_size, don't support converting strings to numbers. That's why calculated expressions whose result matches the parameter type must be used in such parameters. For example:

  • Incorrect: "text_size": "10", "text_size": "@{str_var}".
  • Correct: "text_size": "@{10}", "text_size": "@{int_var}".

Calculating invalid expressions

Let's say the height parameter has the numeric type. The parameter value is set via the @{toInteger('@{var_a}@{var_b}')} expression, which features a template string with two variables. Once calculated, the result of the string is converted to a number using the toInteger function.

Possible errors when using this expression:

  1. Variables don't exist.
  2. The toInteger function doesn't exist.
  3. The string can't be converted to an integer (for example, it contains letters or a fractional part).
  4. The value returned by the function is the incorrect type or violates the contract expected by the height field.

In all the scenarios listed above, the height value can't be calculated correctly, so the system will take the following steps to avoid errors:

  1. The attempt to calculate the expression with default variable values (for example, if the var_a variable value changed from 1 to one, and the toInteger function stopped working correctly).
  2. The attempt to reuse the last successfully calculated value.
  3. If there's no successfully calculated value, the expression takes the default parameter value (in this case, 0).

Data types in expressions

If variables are used in calculated expressions, then, depending on the situation, their values can be converted to internal types of calculated expressions.

The variable value is converted to an internal type if:

  • The variable is used in a template string.
  • The variable is compared to the internal type value (the @{subscribed == true} expression returns true).

The variable value isn't converted to internal type if:

  • The expression consists only of a reference to the variable: "color": "@{color_var}".
  • Two variables of the same type are compared: @{color_var1 == color_var2}.

Example:

{
    "variables": [
        {
            "name": "is_delivered",
            "type": "boolean",
            "value": true
        },
        {
            "name": "order_id",
            "type": "integer",
            "value": 17
        },
        {
            "name": "sum",
            "type": "number",
            "value": 381.3
        }
    ],
    "states": [
        ...
        {
            ...
            "text": "Order#@{order_id} delivered: @{is_delivered} total: @{sum}"
        }
        ...
    ]
}

In this example, expressions with non-string types of variables are used in a string. In this case, the variables' values are converted to strings. After calculating the variables' values, the text parameter looks like this: Order#17 delivered: true total: 381.3.

Internal types of calculated expressions

  • Integer: Integer type. Range: -9223372036854775808..9223372036854775807.
  • Number: Floating-point number. Range: 4.9E-324..1.7976931348623157E308 (the Nan and Infinite values aren't supported).
  • Boolean: Boolean type. Possible values: true, false.
  • String: String.
  • DateTime: Date and time.
  • Color: Color.
  • Url: URL.
  • Dict: Dictionary (associative array).
  • Array: Array.

Note

When converted to a string, a DateTime value is written in the YYYY-MM-DD HH:MM:SS format. To get a string in a different format, use the date formatting functions: formatDateAsLocal for the local time zone and formatDateAsUTC for UTC.

Rules for conversion to internal types

The values of string and numeric type variables are converted to the corresponding internal types. For the remaining variables, the following rules apply:

  • The color type is converted to Color.
  • The url type is converted to Url.
  • The dict type is converted to a Dict dictionary.
  • The array type is converted to an Array.

You can also get Color and Url values from a string using the toColor and toUrl functions. When converted to a string (for example, in a template string), a Color value is written in the #AARRGGBB format, such as #FF001122, and a Url value is written as is.

Operations with types

  • All values of the same type can be checked for equality (==, !=).
  • Comparison operations are available for numeric and DateTime types (>, >=, <, <=).
  • Numeric types support all arithmetic operators. If an operation involves Integer and Number values, the integer is converted to Number: the result of the @{7 + 8.9} expression is 15.9. Operations on other combinations of different types lead to errors. For example, the expression @{'abc' == 7} can't be calculated.

User-defined functions

In addition to built-in functions, you can declare your own.

User-defined functions are declared in the functions block. You cannot use variables in them: you can only pass their values as function arguments. If your function name matches the name of a built-in function, your function will take priority.

Functions can be declared in nested elements. If the name and arguments of several user-defined functions match, the function closest to the call point will take priority.

Field values

Example of function declaration
"functions": [
  {
    "name": "increment",
    "body": "@{value + 1}",
    "return_type": "integer",
    "arguments": [
      {
        "name": "value",
        "type": "integer"
      }
    ]
  }
]

The declared function returns the passed argument "value" increased by 1.

When declaring a function, you need to fill in the following fields:

  • "name" — name. It can contain Latin letters, digits, and the _ character, and can't start with a digit;

  • "body" — function body;

  • "return_type" — type of returned data;

  • "arguments" — list of function arguments. Each argument corresponds to a pair of "name" (name) and "type" (type).

The "return_type" and "type" fields take one of the following types: string, integer, number, boolean, datetime, color, url, dict, array. They correspond to the internal types of calculated expressions.

View an interactive example

Learn more

You can discuss topics of interest in the DivKit user community in Telegram: https://t.me/divkit_community_en.

DivKit Repository