Menu
CoddyTech

Enums and State

Lesson 38 of 48 in Coddy's Dart for PHP Developers course.

PHP 8.1 and later support enum cases as fixed instances; cases() lists them and name exposes the case name. Dart uses values and name for similar operations, and also exposes a zero-based index. PHP backed enum values are explicit int or String values, not a substitute for a Dart index. Both can attach behavior to enum types while preserving fixed cases. Prefer the enum type over unrelated strings when modeling a closed state space. The example uses colors, distinct from the job transitions in the task.

Complete PHP program:

<?php
enum Color { case red; case green; case blue; }
$color = Color::green;
echo $color->name, ':', count(Color::cases()), "\n";

Complete Dart program:

enum Color{red,green,blue}
void main(){final c=Color.green;print('${c.name}:${Color.values.length}');}
challenge icon

Challenge

Easy

Define enum Phase { queued, running, done } in Phase.dart. Implement Job() starting queued, getter phase, and bool advance(): queued becomes running, running becomes done, done remains done and returns false. Other transitions return true. Input is a count from 0 to 100. Call advance that many times and return phase-name:accepted.

Do not print from editable files. The supplied exercise.dart parses input and returns output; the locked driver independently probes the public APIs and prints the result with one newline.

Your code goes in Phase.dart, Job.dart, exercise.dart. main.dart holds the supplied input/output code and cannot be edited.

Try it yourself

import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Phase.dart';
import 'Job.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final j=Job();check(j.phase==Phase.queued && j.advance() && j.phase==Phase.running);check(j.advance() && j.phase==Phase.done && !j.advance());
stdout.writeln(solve(input));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Dart for PHP Developers

Practice on your own: Online Dart compiler