apple/pkl · error · VmException

objectCannotHaveElement

objectCannotHaveElement

Error message

Object of type `{0}` cannot have an element.

What it means

Pkl throws `objectCannotHaveElement` when an element expression (or any member when the literal is elements-only) appears in an object whose class cannot hold elements — typed object classes, and Mappings when the literal contains only elements. In elementsEntriesFallback, a typed parent class or an elements-only Mapping literal triggers this.

Solutions

  1. Remove the element members from the typed object literal.
  2. For a Mapping, replace elements with `[key] = value` entries.
  3. Use a Listing/Dynamic if untyped element members are what you intend.

Example fix

// before
new Server { // typed class
  new { port = 8080 } // element not allowed
}
// after
new Server {
  port = 8080
}
Defensive patterns

Strategy: type-guard

Validate before calling

// Pkl
if (value is Mapping) {
  throw "use [key] = value entries, not elements"
}

Prevention

When it happens

Trigger: Writing `new { ... }` element members in a literal whose parent is a typed object class, or using element syntax inside a Mapping literal that contains only elements.

Common situations: Adding anonymous elements to an object declared with a `: Class` type; writing `new Mapping { ... }` with bare element bodies instead of `[key] = value` entries.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


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

Appendix: source

Thrown at pkl-core/src/main/java/org/pkl/core/ast/expression/literal/SpecializedObjectLiteralNode.java:307

    var parentIsClass = parent instanceof VmClass;
    var parentClass = parentIsClass ? (VmClass) parent : VmUtils.getClass(parent);
    VmUtils.checkIsInstantiable(parentClass, getParentNode());

    var property = findFirstNonDefaultProperty(members);
    if (property != null
        && (parentClass == BaseModule.getListingClass()
            || parentClass == BaseModule.getMappingClass())) {
      throw exceptionBuilder()
          .evalError("objectCannotHaveProperty", parentClass)
          .withSourceSection(property.getHeaderSection())
          .build();
    }

    assert firstElemOrEntry != null;

    if (isTypedObjectClass(parentClass)
        || (isElementsOnly && parentClass == BaseModule.getMappingClass())) {
      throw exceptionBuilder()
          .evalError(
              isElementsOnly ? "objectCannotHaveElement" : "objectCannotHaveEntry", parentClass)
          .withSourceSection(firstElemOrEntry.getHeaderSection())
          .build();
    }

    throw exceptionBuilder().unreachableCode().build();
  }
}

View on GitHub (pinned to f3efcbfc9b)