apple/pkl · error · VmException

methodMustBeConst

methodMustBeConst

Error message

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

What it means

After a virtual method call resolves the target ClassMethod, checkConst enforces that the method is `const` when the call site requires constant evaluation (needsConst). Non-const methods cannot run in const positions, so the error is raised with the method name.

Source

Thrown at pkl-core/src/main/java/org/pkl/core/ast/expression/member/InvokeMethodVirtualNode.java:162

  }

  @Override
  public WrapperNode createWrapper(ProbeNode probe) {
    return new InvokeMethodVirtualNodeWrapper(
        sourceSection,
        methodName,
        argumentNodes,
        lookupMode,
        needsConst,
        argsRequireInference,
        this,
        probe);
  }

  private void checkConst(ClassMethod method) {
    if (needsConst && !method.isConst()) {
      CompilerDirectives.transferToInterpreter();
      throw exceptionBuilder().evalError("methodMustBeConst", methodName.toString()).build();
    }
  }
}

View on GitHub (pinned to f3efcbfc9b)

Solutions

  1. Mark the resolved method `const` in its defining class
  2. Perform the call in a non-const context and store the result in a regular property
  3. Substitute a constant literal or `const` property value

Example fix

// before
const c = obj.compute() // compute not const
// after
// in obj's class:
const function compute() = 1
Defensive patterns

Strategy: validation

Validate before calling

// only call methods marked `const` in const contexts:
// const function compute() = 1

Prevention

When it happens

Trigger: A virtual dispatch (`receiver.method()`) from a const-required context where the resolved ClassMethod.isConst() is false.

Common situations: Dynamic calls into library methods from `const` properties or constant initializers; version upgrades where a previously const method lost its `const` modifier.

Related errors


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