KScript ドキュメント
JA

言語

英語から自動翻訳されています。原文は英語です。

型と検証

コンストラクター

フィールドを持つ型は、値を作るときにそのうちのどれでも受け取ります。construct ブロックはこれを絞り込みます。呼び出し側が渡せるものを列挙し、それ以外のフィールドは値自身の状態になります。

<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"
  • 波かっこ内のフィールドは、他のフィールドと同じように書き、カンマで区切ります。短いリストなら1行に収まります: construct({ name: string })。
  • その後に続くブロックは省略可能です。値が作られるたびに、渡されたフィールドのチェックが終わった後で一度だけ実行され、その型の任意のフィールドを設定できます。
  • constructの外にあるフィールドは、そのデフォルト値から始まります。デフォルト値がない場合は空の状態から始まります: 0、''、false、[]、{ }、またはnull。
  • constructに定義されていないフィールドを渡すとエラーになり、そのエラーには受け付けるフィールドの名前が表示されます。エディターは入力中にこのエラーを報告します。
  • 結合型は、まず基底型のconstructブロックを実行し、その後で自身のブロックを実行します。

型がmodelの入力は、ルートが保持しているレコードを既定値にできます。@inject()は入力の型からモデルを読み取り、入力の名前と同じルートパラメーターを取得します:

<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) は記録を取る際に、モデルのポリシーを尋ねます: construct({ post: Post = @inject(can: read) })。

PostSummary(post: $other) は引き続き与えられた入力を受け取ります。どのルートも応答していない場合、入力を省略するとその入力を名指しするエラーになります。ルールについてはルートのレコードを受け取るを参照してください。

コンポーネントは、同じブロックを使って、ページが設定できる属性と、ページが保持する状態を分けます。