Menu
CoddyTech

空值安全

Coddy 面向 GDScript 开发者的 Dart 课程的第 14 课,共 48 课。

类型为 String 或 int 的 GDScript 变量永远不能保存 null,而未声明类型的 var 或类型为 Object 的变量可以保存 null,对 null 进行成员访问只会在运行时失败。Dart 的可空类型会将缺失情况纳入静态检查。GDScript 没有 ?? 运算符,而且像 user if user else "guest" 这样的真值检查也会替换空字符串,因此要使用显式的 != null 检查来匹配 Dart 的 ??。

问号表示可空类型。检查是否为 null,使用空安全访问,或用 ?? 提供备用值。非空断言可能在运行时失败;对于预期可能缺失的情况,请使用检查。

完整的 GDScript 程序:

extends Node

func _ready() -> void:
    var user = null
    print(user if user != null else "guest")
    user = ""
    print(user == "")

完整的 Dart 程序:

void main(){String? name;print(name??'guest');name='';print(name.isEmpty);}
challenge icon

挑战

简单

实现 firstEven(List<int> values):返回第一个偶数整数,如果没有则返回 null。0 和负偶数也符合条件。输入包含 0 个或多个介于 -100 到 100 之间的整数。输出该数字或 none。

不要从可编辑文件中打印内容。提供的 exercise.dart 会解析输入并返回输出;锁定的驱动程序会独立测试公共 API,并在结果后打印一个换行符。

你的代码应写在 functions.dart、exercise.dart 中。main.dart 包含提供的输入/输出代码,不能编辑。

亲手试试

import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'functions.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
check(firstEven([3,8,2])==8 && firstEven([3])==null);
stdout.writeln(solve(input));
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 GDScript 开发者的 Dart中的所有课

自己练习: Dart 在线编译器