Menu
CoddyTech

Generic Classes

Lesson 36 of 48 in Coddy's Dart for C++ Developers course.

C++ templates are instantiated at compile time: each type argument stamps out its own function, the body is checked against that type (or a C++20 concept), and nothing of T remains at runtime. Dart checks a generic body once against its declared bound, such as T extends Comparable, and keeps type arguments at runtime. Both write explicit type arguments after the function name and can infer them from the arguments.

Generic parameters preserve type relationships across fields, arguments and results. Dart retains type arguments at runtime, so a check such as is List<int> works. Prefer a generic API over dynamic when the caller's type should flow through the operation.

Complete C++ program:

#include <iostream>
#include <string>
#include <vector>
template<typename T>T first(const std::vector<T>&values){return values.front();}
int main(){std::cout<<first<std::string>({"oak","pine"})<<"\n";}

Complete Dart program:

T first<T>(List<T> values)=>values.first;
void main(){print(first<String>(['oak','pine']));}
challenge icon

Challenge

Easy

Implement Box<T>(T value) with mutable private value, getter value, and T replace(T next) that stores next and returns the previous value. It must work for integers and strings. Input is two whitespace-separated words. Output old:new after replacement.

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 Box.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 'Box.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 b=Box<int>(4);check(b.replace(9)==4 && b.value==9);final s=Box<String>('a');check(s.replace('b')=='a' && s.value=='b');
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 C++ Developers

Practice on your own: Online Dart compiler