KScript 文档
ZH

错误代码

KS5018

可能为 null 的值在任何检查之前就被使用了。声明返回 T? 的函数、类型为 T? 的参数或变量,或者没有默认值且标记为 ? 的字段,都可能为 null;对 null 读取字段或对其调用方法会使脚本停止:

<type name="Repo">
  <field name="name" type="string" />
</type>

<fn name="find" params="name: string" returns="Repo?">
  <return value="$name == 'kscript' ? Repo(name: $name) : null" />
</fn>

<echo value="@find('kscript').name" /> <!-- warning: @find() returns Repo? -->
type Repo {
  name: string
}

fn find(name: string): Repo? {
  return $name == 'kscript' ? Repo(name: $name) : null
}

echo @find('kscript').name    // warning: @find() returns Repo?

请先检查,或提供默认值:先 $repo = @find('kscript') 再 if $repo != null { echo $repo.name },或使用 echo @find('kscript')?.name ?? 'none'。编辑器能识别的所有检查,参见 可能为 null 的值。