Home > Blockchain >  How to convert an enum to another type of enum nicely?
How to convert an enum to another type of enum nicely?

Time:01-27

I have an enum of for example 'Status' (Failed , Successful) and I have another enum from a service which has its own Status enum (Failed, Successful, Unknown)

My question is how can I write something quick and nice to convert from their enum to mine?

CodePudding user response:

enum StatusA {failed , successful}
enum StatusB {failed , successful, unknown}

void myServiceB(StatusB state) => print(state);

StatusB convertEnum(StatusA state) {
  var _state = state.toString().split('.')[1];
  return StatusB.values.firstWhere((e) => e.toString().contains(_state));
}


void main(List<String> args) {
  var localState = StatusA.failed;
  myServiceB(convertEnum(localState));
}

Output:

StatusB.failed

Flutter has this function describeEnum, it can be useful too.

CodePudding user response:

You always can just use a Map or a switch statement:

import 'some_other_service.dart' as theirs;

Status statusFromTheirStatus(theirs.Status status) {
  switch (status) {
    case theirs.Status.Unknown:
    case theirs.Status.Failed:
      return Failed;
    case theirs.Status.Successful:
      return Successful;
  }
}

which gives you some flexibility for how to handle Unknown. The above example assumes it's a failure (since typically typically are many ways to fail but only one way to succeed), but you alternatively could, say, throw an exception.

  •  Tags:  
  • Related