elastic/elasticsearch · error · ClassCastException
Cannot apply [+] operation to type [boolean]
Error message
Cannot apply [+] operation to type [boolean]
What it means
Unary plus (+) is defined for all numeric types but not for boolean. DefMath's boolean overload for plus() throws a ClassCastException when a def variable resolves to Boolean and the unary + operator is applied.
Source
Thrown at modules/lang-painless/src/main/java/org/elasticsearch/painless/DefMath.java:130
private static int plus(int v) {
return +v;
}
private static long plus(long v) {
return +v;
}
private static float plus(float v) {
return +v;
}
private static double plus(double v) {
return +v;
}
private static boolean plus(boolean v) {
throw new ClassCastException("Cannot apply [+] operation to type [boolean]");
}
private static Object plus(final Object unary) {
if (unary instanceof Double) {
return +(double) unary;
} else if (unary instanceof Long) {
return +(long) unary;
} else if (unary instanceof Integer) {
return +(int) unary;
} else if (unary instanceof Float) {
return +(float) unary;
} else if (unary instanceof Short) {
return +(short) unary;
} else if (unary instanceof Character) {
return +(char) unary;
} else if (unary instanceof Byte) {
return +(byte) unary;
}View on GitHub (pinned to db6a809a66)
Solutions
- Verify the operand is numeric before applying unary +.
- Use an explicit numeric type declaration instead of def.
- Remove the unary + if it was not intended, or guard with instanceof.
Example fix
// before
def x = doc['flag'].value;
def y = +x;
// after
def x = doc['flag'].value;
if (x instanceof Number) {
def y = +(int) x;
} Defensive patterns
Strategy: type-guard
Validate before calling
// Painless: ensure the value is numeric before unary plus
def x = doc['flag'].value;
if (x instanceof Number) {
def y = +(int) x;
} Type guard
// Painless type guard for numeric types
def isNumeric(def value) {
return value instanceof Number;
} Prevention
- Declare numeric variables with explicit types instead of def.
- Remove unnecessary unary + operators, or guard them with instanceof checks.
- Verify document field mappings are numeric, not boolean, for values used in arithmetic.
When it happens
Trigger: A Painless script applies unary + to a def variable holding a Boolean. Example: `def x = true; def y = +x;`
Common situations: Rarely intentional; usually results from a def variable whose type was inferred from runtime data that happened to be a boolean flag, combined with an expression that uses unary + as a no-op coercion.
Related errors
- Cannot apply [-] operation to type [boolean]
- Cannot apply [-] operation to type [{}].
- Cannot apply [+] operation to type [{}].
- Cannot apply [*] operation to type [boolean]
- Cannot apply [/] operation to type [boolean]
AI-assisted analysis of elastic/elasticsearch@db6a809a66 (2026-08-12).
Data as JSON: /api/errors/53df9b0eb4fd1cf2.
Report an issue: GitHub.