Adam Jenkins
Adam Jenkins

Reputation: 55623

Type inference in dart curried function

I know Typescript's type system allows some pretty intricate inferences, and I'm wondering how far I can push dart.

I want to create a simple utility function that delays a Future by currying.

Future<T> Function(Future<T> fut) delay<T>(Duration dur) =>
    (fut) async => (await Future.wait(
          [Future.delayed(dur), fut],
        ))[1] as T;

The problem with this is that I have to pass T to the delay function, like this:

final delayedPosition<Position>(Duration(seconds: 3));


// later
await delayedPosition(someFutureThatReturnsAPosition);

Ideally, I'd like Dart to infer the type the future is returning so I wouldn't have to specify it myself.

Is this possible? If so, how would it look?

EDIT:

To be clear, what I want to do is to not have to make delay generic and the return type of function returned from delay be inferred from it's argument. This seems to be causing confusion.

e.g.


// declare delay - I don't know what it should look like

final thingThatDelaysAFutureBy3Seconds = delay(Duration(seconds: 3));

// later
final valFromFuture = await thingThatDelaysAFutureBy3Seconds(someFuture);

Upvotes: 1

Views: 128

Answers (1)

Mattia
Mattia

Reputation: 6524

I'm not sure what the problem is here, it is not possible infer the type from the function you provided since there is not context where T is used that can be used to infer the type.

Also the example code you sent is not valid and you are not waiting 5 seconds before running the future as well, but is waiting 5 seconds before returning the future value (but it is ran concurrently with the delay) if you want to run the future after the delay has been passed you should instead use:

Future<T> Function(Future<T> fut) delay<T>(Duration dur) => (fut) async {
      await Future.delayed(dur);
      return fut;
    };

Example:

Future<void> main(List<String> arguments) async {
  var f = delay<int>(Duration(seconds: 5));
  var v = await f(f1()); // Inferred as int
  print(v);
}

Future<int> f1() => Future.value(1);

Upvotes: 1

Related Questions