Menu
CoddyTech

空值安全

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

Python 使用 None 和显式的 is None 检查。Dart 的可空类型会将值缺失纳入静态检查。只有在值缺失时才使用 ??;Python 的 or 还会替换空字符串、0 和其他假值,因此两者并不等价。

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

完整的 Python 程序:

name=None
print(name if name is not None else 'guest')
name=''
print(name=='')

完整的 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自我测试

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

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

自己练习: Dart 在线编译器