Dart by Example: Final

Final objects are immutable

  1. main() {
  2. // final variables are single-assignment:
  3. final foo = "hello";
  4. try {
  5. foo = 'goodbye'; // runtime error; already assigned
  6. } catch(e) {
  7. print('error');
  8. }
  9. var pos = new Position(4);
  10. try {
  11. pos.x = 100; // runtime error
  12. } catch(e) {
  13. print('error');
  14. }
  15. }
  16. class Position {
  17. final int x;
  18. final int y;
  19. Position(this.x) : y = 0;
  20. }
  21.  
  1. $ dart final.dart
  2. error
  3. error

by @jryanio | source | license