Joe M.
Joe M.

Reputation: 609

Is it possible to specify only some of Type Arguments in a generic function?

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).

Upvotes: 1

Views: 29

Answers (1)

lrn
lrn

Reputation: 71683

You cannot partially apply type parameters. You need to wrap the function to do that:

T? tryOrNullOnFormatException<T>(T Function() computation) {
  return tryOrNull<FormatException, T>(computation);
}

If you do this often, you can abstract the wrapper:

T? Function<T>(T Function()) tryOrNull2<E>() => 
    <T>(T Function() computation) => tryOrNull<E, T>(computation);

which you can then use as:

DateTime? parseDate(String date) {
  return tryOrNull2<FormatException>()(() => DateTime.parse(date));
}

Alternatively, you can write both types at the call point, if you know them:

DateTime? parseDate(String date) {
  return tryOrNull<FormatException, DateTime>(() => DateTime.parse(date));
}

I can see why that's annoying, but for type parameters, you always need to provide either all or none.

Upvotes: 2

Related Questions