apple/pkl · error · VmException

methodMustBeConst

methodMustBeConst

Error message

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

What it means

Same const-ness rule as class methods but for object (definition) methods: when the call site requires a constant value, InvokeLexicalObjectMethodNode looks up the member on the owner and throws if its modifiers lack the `const` flag.

Source

Thrown at pkl-core/src/main/java/org/pkl/core/ast/expression/member/InvokeLexicalObjectMethodNode.java:43

/** A non-virtual call of an object method that is lexically scoped. */
public final class InvokeLexicalObjectMethodNode extends AbstractInvokeLexicalMethodNode {
  public InvokeLexicalObjectMethodNode(
      SourceSection sourceSection,
      Identifier methodName,
      int levelsUp,
      ExpressionNode[] argumentNodes,
      boolean needsConst,
      boolean argsRequireInference) {
    super(sourceSection, methodName, levelsUp, argumentNodes, needsConst, 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. Mark the object method `const` in its definition
  2. Replace the call with a `const` property or literal
  3. Reconsider whether the call site truly needs const and relax it

Example fix

// before
x {
  function helper() = 42
}
constY = x.helper() // const context
// after
x {
  const function helper() = 42
}
Defensive patterns

Strategy: validation

Validate before calling

// declare object methods const when they should be usable in const positions:
// const function helper() = 42

Prevention

When it happens

Trigger: An object method invoked via lexical scope from a const-requiring position; doCheckConst finds the member and VmModifier.isConst(modifiers) is false.

Common situations: Calling a non-const object method while computing a const property or module-level constant; methods copied from non-const examples into const contexts.

Related errors


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