Composition Across Files
Lesson 31 of 48 in Coddy's Dart for Go Developers course.
A Go struct shares a collaborator only when its field is a pointer such as *Speaker; a field of type Speaker would copy the struct at assignment. Every Dart class-typed field holds a reference, so Radio(s) always shares s and there is no value copy to opt into. final prevents rebinding the field but does not freeze the referenced object; Go has no final fields at all. In both languages garbage collection is not a deterministic resource-release protocol: Go code uses defer and Close, Dart code uses try/finally and explicit close methods.
Store collaborator references in fields and import their libraries explicitly: Go files in one package see each other without imports, but every Dart file is its own library, so the file that uses Speaker must import the file that declares it. A final field prevents reassignment without freezing its collaborator. Object garbage collection is separate from resource-management contracts.
Complete Go program:
package main
import "fmt"
type Speaker struct{ tone string }
type Radio struct{ speaker *Speaker }
func (r Radio) play() string { return r.speaker.tone }
func main() {
s := &Speaker{tone: "soft"}
r := Radio{speaker: s}
s.tone = "loud"
fmt.Println(r.play())
}
Complete Dart program:
class Speaker{String tone='soft';}
class Radio{final Speaker speaker;Radio(this.speaker);String play()=>speaker.tone;}
void main(){final s=Speaker();final r=Radio(s);s.tone='loud';print(r.play());}Challenge
EasyImplement Stop(String name,int minutes) with public final fields. Implement Route() with add(Stop stop), getter total, and names() returning stop names in insertion order as a fresh list. Input contains complete name/minutes pairs, at most 100, minutes 0 through 100. Output total|names with comma-separated names, using empty for no stops.
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 Stop.dart, Route.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 'Stop.dart';
import 'Route.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 r=Route();r.add(Stop('x',7));r.add(Stop('y',4));check(r.total==11 && r.names().join(',')=='x,y');r.names().clear();check(r.names().length==2 && Route().total==0);
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 Go 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 Inventory3Functions 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