为什么我需要 return null 类型为 nullable return 的函数?
Why do I need to return null for functions with nullable return type?
我在这段代码中收到警告:
Future<int?> foo() async {
if (someCondition) return 42;
}
This function has a nullable return type of 'FutureOr<int?>', but ends without returning a value.
我告诉 Dart Future 可能会以可空类型 int?
完成,所以为什么我必须明确地 return null
才能摆脱警告?
这是警告,不是错误。警告是针对技术上合法但很可能是编程错误的事情。编写该代码的人更有可能忘记处理代码路径,而不是他们故意想要隐式 return null
。明确的 return null
还使意图清晰,因此更具可读性。
我在这段代码中收到警告:
Future<int?> foo() async {
if (someCondition) return 42;
}
This function has a nullable return type of 'FutureOr<int?>', but ends without returning a value.
我告诉 Dart Future 可能会以可空类型 int?
完成,所以为什么我必须明确地 return null
才能摆脱警告?
这是警告,不是错误。警告是针对技术上合法但很可能是编程错误的事情。编写该代码的人更有可能忘记处理代码路径,而不是他们故意想要隐式 return null
。明确的 return null
还使意图清晰,因此更具可读性。