Replies: 1 comment
-
|
Hi there! If I'm interpreting your ask correctly, Pkl already provides what you're looking for. Building from your example: class Config {
roles: Listing<Role> = new { // note: no `new Listing`, Pkl infers the type for `new` is `Listing<Role>`
new { name = "default" } // note: no `new Role`, Pkl infers the type for new within the `Listing` is `Role`
}
}Note I've elided explicit types for your There are a few ways a user might use this class: // completely replace/override the default value in the class
config1: Config = new {
roles = new Listing<Role> { ... } // or `new Listing`
}
// replace/override the value with a new one that amends the default value in the class, adding more elements
config2: Config = new {
roles = new { ... }
}
// amend the parent value (in this case the default value in the class), adding more elements
config3: Config = new {
roles { ... }
}
// in the scenario the result is the same as config2 but the meaning is subtly different
// and manifests when amending values, not instantiating classes
// see https://pkl-lang.org/main/current/language-reference/index.html#implicitly-typed-newNote The third method—parent amending—is the most common way that Pkl schemas are amended. Finally, since you want to enforce that some default role is always present, using a type constraint is a typical approach: const defaultRole: Role = new { name = "default" }
class Config {
roles: Listing<Role>(toSet().contains(defaultRole)) = new {
defaultRole
}
}Another approach here is splitting the property into a class Config {
hidden roles: Listing<Role>
fixed effectiveRoles: Listing<Role> = (roles) {
new { name = "default" }
}
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi, I just wanted to ask if it’s possible to add something like the following. It would be very useful!
Problem Statement
Currently, PKL supports default values for scalar fields:
However, there's no way to define default values for
Listingfields that get merged with user-provided items or injected when certain items are missing:Use Case
When defining configuration schemas, it's common to have lists where:
Currently, if you define:
The default is completely replaced when a user provides any value. There's no way to express "always include these items, plus whatever the user adds."
Current Workarounds
All workarounds have significant drawbacks:
Desired Behavior Suggestions
Merge semantics for Listing defaults
A way to specify that default items should be merged with user-provided items:
Conditional injection constraint
A constraint that injects an item if a predicate isn't satisfied:
defaultItemsmodifierSimilar to how
defaultworks for scalar fields:Beta Was this translation helpful? Give feedback.
All reactions