Skip to content

Instantly share code, notes, and snippets.

@redbrogdon
Last active May 18, 2019 03:37
Show Gist options
  • Save redbrogdon/4bf47cf7e11bc5902e605a3efc3183ec to your computer and use it in GitHub Desktop.
Save redbrogdon/4bf47cf7e11bc5902e605a3efc3183ec to your computer and use it in GitHub Desktop.
DartPad Cheatsheet Codelab - 12 - Initializer lists
There are two assignments that need to happen: letterOne should be word[0], and letterTwo should be word[1].
class FirstTwoLetters {
final String letterOne;
final String letterTwo;
// Create a constructor with an initializer list here:
FirstTwoLetters(String word)
...
}
class FirstTwoLetters {
final String letterOne;
final String letterTwo;
FirstTwoLetters(String word)
: letterOne = word[0],
letterTwo = word[1];
}
void main() {
final errs = <String>[];
try {
final result = FirstTwoLetters('My String');
if (result == null) {
errs.add('Called FirstTwoLetters(\'My String\') and got a null in response.');
} else {
if (result.letterOne != 'M') {
errs.add('Called FirstTwoLetters(\'My String\') and got an object with letterOne equal to \'${result.letterOne}\' instead of the expected value (\'M\').');
}
if (result.letterTwo != 'y') {
errs.add('Called FirstTwoLetters(\'My String\') and got an object with letterTwo equal to \'${result.letterTwo}\' instead of the expected value (\'y\').');
}
}
} catch (e) {
_result(false, ['Called FirstTwoLetters(\'My String\') and got an exception of type ${e.runtimeType}.']);
}
bool caughtException = false;
try {
FirstTwoLetters('');
} catch (e) {
caughtException = true;
}
if (!caughtException) {
errs.add('Called FirstTwoLetters(\'\') and didn\'t get an exception from the failed assertion.');
}
if (errs.isEmpty) {
_result(true);
} else {
_result(false, errs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment