Enums and State
Lesson 38 of 48 in Coddy's Dart for Kotlin Developers course.
Kotlin enum classes and Dart enums each provide fixed named instances. Kotlin ordinal and Dart index reflect declaration order rather than a stable business identifier. Use explicit data when a durable external code is needed.
An enum defines a fixed set of named instances. name exposes the declared case name and values lists all cases. Enhanced enums add members but do not turn arbitrary integers into valid instances.
Complete Kotlin program:
enum class Color{red,green,blue}
fun main(){println("${Color.green.name}:${Color.values().size}")}
Complete Dart program:
enum Color{red,green,blue}
void main(){final c=Color.green;print('${c.name}:${Color.values.length}');}Challenge
EasyDefine 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));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Dart for Kotlin Developers
1First Dart Programs
Run Dart FilesOutput and CommentsImports and LibrariesBindings and TypesNumeric OperationsRecap: Parcel Invoice4Collection Pipelines
Iterables and LazinessMaps and Missing KeysSets and MembershipClosures and CallbacksSorting and ComparatorsRecap: Word Inventory7Contracts and Reuse
Inheritance and OverridesImplicit InterfacesAbstract Base BehaviorGeneric ClassesMixins and ReuseEnums and StateRecap: Transform Pipeline3Functions and Values
Functions and ReturnsNamed ParametersNull SafetyStrings and UnicodeLists and MutationRecap: Record Readings6Objects and State
Classes and InstancesConstructors and FactoriesProperties and PrivacyIdentity and CopiesComposition Across FilesRecap: Bounded Counter9Parcel Depot Project
Depot: Valid ItemsDepot: Register StockPractice on your own: Online Dart compiler