Home > Net >  Flutter : it is possible to implement custom type union?
Flutter : it is possible to implement custom type union?

Time:12-20

in dart there is such feature like abstract class FutureOr<T> {}. The FutureOr<int> type is actually the "type union" of the types int and Future.

can we imitate this ?

abstract class AnimalOr<T> {}

abstract class Animal{}

abstract class Human{}

is it possible to do something like this? :

AnimalOr<T> pickCreature<T> (){
  final result = calculate();
  if(conditionIsMet){
    return result as T;
  }
  return result as Animal;
 }

AnimalOr<Human> creature = pickCreature<Human>();

CodePudding user response:

While the FutureOr<X> type is actually useful to say "I will get X, but I don't know if it will be synchronous or asynchronous. Your type does not have any such implication. A FutureOr<X> at some point (except exceptions obviously) will always be reduced to an X, your type will always stay "either one or the other". You cannot get one from the other.

It seems like you are looking for an Either<TLeft, TRight> type. You can write one youself, or you can look at packages that already did this.

For example

  • Related