Strings
Interpolation
${expr}
Inside a string literal, ${expression} inserts a value computed at runtime.
Program
Play the program to embed a computed age in a sentence.
interpolation.dart
Replay: real traced execution (multi-file project)
void main() {
var name = 'Ada';
var age = 36;
print('${name} is ${age + 1} next year');
}
name ← Ada
1void main() {2 var name = 'Ada';3 var age = 36;values this stepAdanameage ← 36
2var name = 'Ada';3var age = 36;4print('${name} is ${age + 1} next year');values this step36ageprint('${name} is ${age + 1} next year');
3 var age = 36;4 print('${name} is ${age + 1} next year');5}outputAda is 37 next yearvalues this stepAdaname36age
Follow the Values
namestarts asAda.agestarts as36.${name}insertsAdainto the string.${age + 1}computes37.- The program prints
Ada is 37 next year. | piece | value | | --- | --- | |${name}| Ada | |${age + 1}| 37 | | output | Ada is 37 next year |
$name
Simple identifier interpolation.
${expr}
Full-expression interpolation inside `${...}`.
immutable
The original `name` and `age` are unchanged.
Exercise: interpolation.dart
Reproduce Ada is 37 next year, then trace how name Ada and age + 1 equals 37 create the sentence.