apple/pkl · error · VmException

typeMismatch

typeMismatch

Error message

Expected value of type `{0}`, but got type `{1}`.

What it means

The condition of an `if (cond) ... else ...` expression must be a Boolean. IfElseNode.evaluateCondition calls conditionNode.executeBoolean; when the condition expression produces a non-Boolean value (UnexpectedResultException), it throws a typeMismatch error stating the expected type `Boolean` and the actual type of the result.

Solutions

  1. Make the condition explicitly Boolean, e.g. `if (x != null)`, `if (!list.isEmpty())`, `if (value == expected)`
  2. Fix forgotten parentheses: use `list.isEmpty()` (a Boolean method) rather than `list.isEmpty`
  3. Check the condition's declared type in its definition and convert it (e.g. `x > 0` instead of `x`)
  4. If the condition may be null, write `if (cond != null && cond)` style guards

Example fix

// before
name: String = "srv"
if (name) { ... } // ERROR: typeMismatch, got String
// after
if (!name.isEmpty()) { ... }
Defensive patterns

Strategy: validation

Validate before calling

// ensure the if-condition is a Boolean expression in Pkl
// bad:  if (name)
// good: if (!name.isEmpty())
// good: if (x != null)

Type guard

null

Try / catch

null

Prevention

When it happens

Trigger: `if (cond)` where cond evaluates to a non-Boolean: e.g. `if (x)` with `x: Int`, `if (list.isEmpty)` typo'd to `if (list)`, or `if (someNullable)` where the value is String/Int/Null instead of a Boolean predicate call.

Common situations: Migrating from a dynamic-language habit of truthy checks (`if (name)`) into Pkl which requires an explicit Boolean; calling a property instead of a method (forgetting `()` on `isEmpty()`); comparing with `=`/`==` mistakes that yield non-Boolean types.

Understand the failure class

Background: Type mismatch errors: IllegalArgumentException, TypeError and type guards across 150 open-source libraries — this error's family across 150 libraries.

Related errors


AI-assisted analysis of apple/pkl@f3efcbfc9b (2026-09-08). Data as JSON: /api/errors/dfed35bcc33a7455. Report an issue: GitHub.

Appendix: source

Thrown at pkl-core/src/main/java/org/pkl/core/ast/expression/ternary/IfElseNode.java:57

    super(sourceSection);
    this.conditionNode = conditionNode;
    this.thenNode = thenNode;
    this.elseNode = elseNode;
  }

  @Override
  public Object executeGeneric(VirtualFrame frame) {
    return evaluateCondition(frame)
        ? thenNode.executeGeneric(frame)
        : elseNode.executeGeneric(frame);
  }

  private boolean evaluateCondition(VirtualFrame frame) {
    try {
      return conditionNode.executeBoolean(frame);
    } catch (UnexpectedResultException e) {
      CompilerDirectives.transferToInterpreter();
      throw exceptionBuilder()
          .typeMismatch(e.getResult(), BaseModule.getBooleanClass())
          .withSourceSection(conditionNode.getSourceSection())
          .build();
    }
  }
}

View on GitHub (pinned to f3efcbfc9b)