apple/pkl · error · VmException

methodMustBeConst

methodMustBeConst

Error message

Cannot call method `{0}` from here because it is not `const`.

What it means

Qualified calls to object methods are checked by InvokeQualifiedObjectMethodNode.doCheckConst: the member is fetched via owner.getMember(methodName) and if VmModifier.isConst(member.getModifiers()) is false in a const-requiring call site, this error is thrown.

Source

Thrown at pkl-core/src/main/java/org/pkl/core/ast/expression/member/InvokeQualifiedObjectMethodNode.java:49

      ExpressionNode[] argumentNodes,
      boolean needsConst,
      ExpressionNode getReceiverNode,
      boolean argsRequireInference) {
    super(
        sourceSection,
        methodName,
        argumentNodes,
        needsConst,
        getReceiverNode,
        argsRequireInference);
  }

  @Override
  protected void doCheckConst(VmObjectLike owner) {
    var member = owner.getMember(methodName);
    assert member != null;
    if (!VmModifier.isConst(member.getModifiers())) {
      throw exceptionBuilder().evalError("methodMustBeConst", methodName).build();
    }
  }

  @Override
  protected Method getMethod(VmObjectLike owner) {
    var member = owner.getMember(methodName);
    assert member != null && member.isLocal();
    var method = (ObjectMethodNode) member.getMemberNode();
    assert method != null;
    return method;
  }
}

View on GitHub (pinned to f3efcbfc9b)

Solutions

  1. Declare the object method `const`
  2. Cache the value in a non-const property and reference that
  3. Inline the constant computation

Example fix

// before
mod {
  function calc() = 2
}
const k = mod.calc()
// after
mod {
  const function calc() = 2
}
Defensive patterns

Strategy: validation

Validate before calling

// ensure the object method is const before qualified const-context calls:
// const function calc() = 2

Prevention

When it happens

Trigger: `obj.method()` (qualified object method call) evaluated where a constant is required and the object method lacks the `const` modifier.

Common situations: Reading computed values from a module object in a const position; methods defined by third-party modules without const modifiers.

Related errors


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