Home > other >  How to print only the value of an enum?
How to print only the value of an enum?

Time:01-20

enum Move { rock, paper, scissors }

var playerMove = Move.rock;

print('Player played :${playerMove.name}'); <--- this line here gives me an error

print('AI played :${aiMove.name}'); <--- this line works perfectly though

this is the error code: Unhandled exception: NoSuchMethodError: Class 'Move' has no instance getter 'name'. Receiver: Instance of 'Move' Tried calling: name

import 'dart:io';

import 'dart:math';

enum Move { rock, paper, scissors }
void main() {
  while (true) {
    final rng = Random();
    stdout.write('Rock, paper, scissors (r,p,s): ');
    final input = stdin.readLineSync();
    if (input == 'r' || input == 'p' || input == 's') {
      var playerMove;
      if (input == 'r') {
        playerMove = Move.rock;
      } else if (input == 'p') {
        playerMove = Move.paper;
      } else {
        playerMove = Move.scissors;
      }
      var random = rng.nextInt(3);
      var aiMove = Move.values[random];
      print('Input: $input');
      print('Player played :${playerMove.name}');
      print('AI played     :${aiMove.name}');
      if (playerMove == aiMove) {
        print("It's a draw");
      } else if (playerMove == Move.paper && aiMove == Move.rock ||
          playerMove == Move.rock && aiMove == Move.scissors ||
          playerMove == Move.scissors && aiMove == Move.paper) {
        print('Player win');
      } else {
        print('You lose');
      }
    } else if (input == 'q') {
      break;
    } else {
      print('Invalid input');
    }
  }
}

CodePudding user response:

.name is an extension on enum. Dart extensions are static: they are compile-time syntactic sugar, and they therefore require that the object's type be known at compilation time.

You have code:

var playerMove;
if (input == 'r') {
  playerMove = Move.rock;
}
...

var playerMove; does not specify a type for the variable, and there is no initializer to infer its type from. It therefore is implicitly declared as dynamic, and extensions on enum will not be applied to it.

You can fix it by specifying an explicit type:

Move playerMove;
  •  Tags:  
  • Related