You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart中如何根据参数可空性让方法返回对应类型?求优雅实现方案

更优雅的实现方案:利用Dart泛型或扩展方法关联参数与返回类型

方案一:泛型函数

通过泛型约束让返回类型与参数类型自动关联,无需编写两个独立方法:

T doSomething<T extends String?>(T str) {
  if (str == null) {
    return null as T;
  }
  return 'did something with $str' as T;
}

说明:

  • 泛型T extends String?限定参数只能是String或String?类型
  • 传入非null的String时,Dart会自动将T推断为String,返回值必然是非null的String(类型转换安全,因为此时输入非null,生成的结果也是非null字符串)
  • 传入String?类型(可能为null)时,T被推断为String?,若参数为null则返回null,否则返回处理后的字符串,完全匹配需求

方案二:扩展方法

利用Dart的扩展特性,给String?类型添加方法,自然实现返回类型随调用者类型变化:

extension StringProcessor on String? {
  String? doSomething() {
    final self = this;
    return self == null ? null : 'did something with $self';
  }
}

使用方式:

// 非null String调用,返回String
String result1 = "test".doSomething();

// nullable String?调用,返回String?
String? result2 = null.doSomething();
String? result3 = (Math.random() > 0.5 ? "hello" : null).doSomething();

这两种方案都避免了重复代码,完美实现了你需要的“参数类型决定返回类型”的效果。

内容的提问来源于stack exchange,提问作者Magnus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 01:42:43