示例工程 ch03-types-collections

ch03-types-collections/lib/null_safety.dart

dart · 3.0 KB

/// null 安全:Dart 2.12 起,`null` 被类型系统约束。
///
/// 对照 C:`NULL` 是裸指针,解引用即 UB;编译器一声不吭。
/// 对照 Go:`nil` 是零值,接口/指针/chan 都能是 nil,用错就 panic。
/// 对照 Dart:`String` 与 `String?` 是**两种类型**,前者永不为 null,编译器保证。
library;
 
/// 参数是 `String?`:调用方可以传 null,函数内部必须处理。
/// 返回值是 `String`:调用方拿到的永不为 null。
String displayName(String? name) {
  // 空字符串也当"没名字"处理;?. 是"如果是 null 就短路成 null"。
  if (name == null || name.trim().isEmpty) return 'anonymous';
  return name.trim();
}
 
/// 类型提升(type promotion):`if (s == null) return ...;` 之后,
/// 这个局部变量在剩余控制流里被**自动收窄**成 `String`,不需要 `!`。
String shout(String? s) {
  if (s == null) return '...';
  return s.toUpperCase(); // 这里 s 已经是 String,写 s! 反而会被 lint 骂
}
 
/// `??` 提供默认值;`??=` 只在为 null 时赋值。
String configOrDefault(Map<String, String> cfg, String key) =>
    cfg[key] ?? 'default';
 
/// 可空返回值:调用方必须处理 null,否则编译不过。
String? firstWord(String text) {
  final parts = text.trim().split(RegExp(r'\s+'));
  return parts.isEmpty || parts.first.isEmpty ? null : parts.first;
}
 
/// 安全的链式访问:`?.` 让整条链短路。
String cityOfUser(Map<String, Object?>? user) {
  final address = user?['address'];
  if (address is! Map<String, Object?>) return '未知';
  return (address['city'] as String?) ?? '未知';
}
 
/// `late final`:延迟初始化,第一次读取时才求值,之后只读。
/// C 里的"懒汉初始化"、Go 里的 `sync.Once`,这里是一个字段关键字。
class LazyConfig {
  /// 计数器只为了让测试能证明"真的只算一次"。
  int computeCount = 0;
 
  late final String dbPath = _computePath();
 
  String _computePath() {
    computeCount++;
    return '/tmp/ch03-app.db';
  }
}
 
/// `late` 的危险面:没有初始化就读取 → `LateInitializationError`(运行期)。
/// 它比 `String?` 危险,因为它把检查从编译期挪到了运行期,只在你确定"一定会赋值"时用。
String uninitializedLate() {
  late String value;
  final list = <String>[];
  if (list.isNotEmpty) value = list.first;
  return value; // 这里会抛 LateInitializationError
}
 
/// `!` 是"我保证不是 null"的运行期断言。
/// 用错就 `Null check operator used on a null value`——只是比 C 的 segfault 好一点。
String unsafeBang(String? s) => s!;
 
/// 集合中取不到元素时返回 null,而不是像 C 那样给你一段垃圾内存。
int? firstOrNull(List<int> xs) => xs.isEmpty ? null : xs.first;
 
/// Map 查找返回可空值,等价 Go 的 `v, ok := m[k]`;但 Go 里 `v` 是零值,
/// Dart 里是 `null`——两者都能靠 `??` 或判空区分"不存在"和"值为零"。
int? lookup(Map<String, int> m, String key) => m[key];