Home > Mobile >  return type for getter problem when returning enum
return type for getter problem when returning enum

Time:07-08

In parity I am attempting to return a string which is extracted using enum.enum_entry.name property bit I am getting an error.

Code :

enum SerialPortParity {
  none,
  even,
  odd,
  mark,
  space,
}

 int _parity = UsbPort.PARITY_NONE;
  String get parity {
    switch (_parity) {
      case UsbPort.PARITY_NONE:
        return SerialPortParity.none.name;
      case UsbPort.PARITY_EVEN:
        return SerialPortParity.even.name;
      case UsbPort.PARITY_ODD:
        return SerialPortParity.odd.name;
      case UsbPort.PARITY_MARK:
        return SerialPortParity.mark.name;
      case UsbPort.PARITY_SPACE:
        return SerialPortParity.space.name;
      default:
        return SerialPortParity.none.name;
    }
  }

Error :

The return type of getter 'parity' is 'String' which isn't a subtype of the type 'SerialPortParity' of its setter 'parity'.
Try changing the types so that they are compatible.

Setter:

set parity(SerialPortParity parity) {
    switch (parity) {
      case SerialPortParity.none:
        _parity = UsbPort.PARITY_NONE;
        break;
      case SerialPortParity.even:
        _parity = UsbPort.PARITY_EVEN;
        break;
      case SerialPortParity.odd:
        _parity = UsbPort.PARITY_ODD;
        break;
      case SerialPortParity.mark:
        _parity = UsbPort.PARITY_MARK;
        break;
      case SerialPortParity.space:
        _parity = UsbPort.PARITY_SPACE;
        break;
      default:
        //No Change
        break;
    }
  }

CodePudding user response:

The error says your getter and setter must be the same type. You have a setter of parity somewhere in your code thay you don't show here. But you can fix this by changing the return type of your getter to SerialPortParity.

Or changing the setter param type to String.

enum SerialPortParity {
  none,
  even,
  odd,
  mark,
  space,
}

int _parity = UsbPort.PARITY_NONE;

String get parityName {
  return parity.name;
}
SerialPortParity get parity {
    switch (_parity) {
      case UsbPort.PARITY_NONE:
        return SerialPortParity.none;
      case UsbPort.PARITY_EVEN:
        return SerialPortParity.even;
      case UsbPort.PARITY_ODD:
        return SerialPortParity.odd;
      case UsbPort.PARITY_MARK:
        return SerialPortParity.mark;
      case UsbPort.PARITY_SPACE:
        return SerialPortParity.space;
      default:
        return SerialPortParity.none;
    }
}

CodePudding user response:

Add a to String

return SerialPortParity.none.name.toString();
  • Related