The following function is an example that represents a more complex situation that can not be simplified:
String? intToString(int? i) {
if (i == null) return null;
return i.toString();
}
Can this function be rewritten using generics in a way that its return type is a String instead of a String? when the parameter is an int?
To make things clearer, here is an example where the nullability of the return type depends on the argument:
void main() {
List<String> non_nullable = ['A', 'B'];
print(first(non_nullable).length); // Does compile
List<String?> nullable = ['A', 'B', null];
print(first(nullable).length); // Fails to compile
}
T first<T>(List<T> ts) {
return ts[0];
}
But can I do this when the parameter type and the return type are different?
String intToString(int)andString? intToString(int?)overloads. But alas, Dart currently does not support overloaded functions. You instead will have to name them differently.