Constructors
A type with fields takes any of them when a value is made. A construct block narrows that: it lists what a caller may pass, and every other field becomes the value's own state.
<import package="KScript.Math" />
<type name="Point">
<construct>
<field name="x" type="number" />
<field name="y" type="number" default="0" />
<do>.length = (.x * .x + .y * .y)->sqrt()</do>
</construct>
<field name="length" type="number" />
</type>
<let name="point" value="Point(x: 3, y: 4)" />
<echo>{$point.x}, {$point.y} is {$point.length} from the origin</echo>import KScript.Math
type Point {
construct({
x: number,
y: number = 0,
}) {
.length = (.x * .x + .y * .y)->sqrt()
}
length: number
}
$point = Point(x: 3, y: 4)
echo "{$point.x}, {$point.y} is {$point.length} from the origin"- The fields in the braces are written like any other field, separated by commas. A short list fits on one line:
construct({ name: string }). - The block after them is optional. It runs once each time a value is made, after the passed fields are checked, and can set any field of the type.
- A field outside
constructstarts with its default. Without one it starts empty:0,'',false,[],{ }or null. - Passing a field that
constructdoesn't list is an error that names the fields it takes. The editor reports it as you type. - A joined type runs its bases'
constructblocks first, then its own.
An input whose type is a model can default to the record the route holds. @inject() reads the model from the input's type and takes the route parameter with the input's name:
<type name="PostSummary">
<construct>
<field name="post" type="Post" default="@inject()" />
<do>.words = .post.body->split(' ')->count()</do>
</construct>
<field name="words" type="int" />
</type>
<!-- a controller on /posts/{post} -->
<fn name="stats" value="PostSummary()" />type PostSummary {
construct({ post: Post = @inject() }) {
.words = .post.body->split(' ')->count()
}
words: int
}
// a controller on /posts/{post}
fn stats() => PostSummary()@inject(can: read) asks the model's policy as the record is taken: construct({ post: Post = @inject(can: read) }).
PostSummary(post: $other) still takes what it is given. Where no route is being answered, leaving the input out is an error that names it. See taking the route's record for the rules.
A component uses the same block to separate the attributes a page may set from the state it keeps.