apple/pkl · error · VmException

methodMustBeConst

methodMustBeConst

Error message

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

What it means

Pkl requires that methods invoked in `const` contexts (e.g. inside `const` property values or module constant positions) be declared `const`. InvokeLexicalClassMethodNode checks the lexically resolved class method and throws this error if `method.isConst()` is false. Const expressions must be evaluable without arbitrary side effects.

Source

Thrown at pkl-core/src/main/java/org/pkl/core/ast/expression/member/InvokeLexicalClassMethodNode.java:44

 * abstract, and is lexically scoped).
 */
public final class InvokeLexicalClassMethodNode extends AbstractInvokeLexicalMethodNode {
  public InvokeLexicalClassMethodNode(
      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 method = owner.getVmClass().getDeclaredMethod(methodName);
    assert method != null;
    if (!method.isConst()) {
      throw exceptionBuilder().evalError("methodMustBeConst", methodName).build();
    }
  }

  @Override
  protected Method getMethod(VmObjectLike owner) {
    var method = owner.getVmClass().getDeclaredMethod(methodName);
    assert method != null;
    return method;
  }
}

View on GitHub (pinned to f3efcbfc9b)

Solutions

  1. Declare the method `const`: `function foo(): Int = ...` becomes `const function foo(): Int = ...` if it qualifies
  2. Inline a constant expression instead of calling the method
  3. Remove the call from the const-required position

Example fix

// before
class Config {
  function size(): Int = 3
  x: Int = size() // used in const context
}
// after
class Config {
  const function size(): Int = 3
  x: Int = size()
}
Defensive patterns

Strategy: validation

Validate before calling

// check the method is declared const before calling in const context:
// const function size(): Int = 3

Prevention

When it happens

Trigger: Calling a class method via a lexical (implicit receiver) reference from a position that requires const-ness (doCheckConst), where the method is not declared `const`.

Common situations: Using a helper function in a `const` property, default value, or annotation-style position; library method not marked `const` while callers expect constant evaluation.

Related errors


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