I am trying to extract a behavior of "check for an exception & return null if the exception was thrown" into a function, like this:
T? tryOrNull<TException, T>(T Function() innerFunction) {
try {
return innerFunction();
} on TException {
return null;
}
}
// usage
DateTime? parseDate(String date) {
return tryOrNull<FormatException, DateTime>(() => DateTime.parse(date));
}
Q: is it possible to somehow define the tryOrNull so that I do not need to specify the second type argument (the Datetime)?
I would like for it to be usable like this, as there imo should be no need to specify the Datetime - the type can be inferred from the type of provided innerFunction.
// usage
DateTime? parseDate(String date) {
return tryOrNull2<FormatException>(() => DateTime.parse(date));
}
Or to rephrase, How to specify the Exception's type better?
I am thinking something like Scala's Try(innerFunction).toOption, but with Dart's null-safety (which is imo so much more convenient than using Options).