Unmodifiable collections

The collection framework has unmodifiable versions of the existing collections with the following advantages:

  • To make a collection immutable once it has been built and not modify the original collection to guarantee absolute immutability, although the elements in that collection are still mutable
  • To allow read-only access to your data structure from the client code and the client code can look into it without modifying it while you have full access to the original collection

The unmodifiable list

The unmodifiable collection based on the List class is UnmodifiableListView. It creates an unmodifiable list backed by the source provided via the argument of the constructor:

import 'dart:collection';

void main() {
  var list = new List.from([1, 2, 3, 4]);
  list.add(5);
  var unmodifiable = new UnmodifiableListView(list);
  unmodifiable.add(6);
}

The execution fails when we try adding a new element to an unmodifiable collection, as shown in the following code:

Unsupported operation: Cannot add to an unmodifiable list
#0 ListBase&&UnmodifiableListMixin.add (…)
#1 main (file:///…/bin/unmodifiable.dart:7:19)
…

The following diagram shows the class hierarchy of UnmodifiableListView:

The unmodifiable list

The unmodifiable map

Another unmodifiable collection is UnmodifiableMapView, which is based on the Map class. It disallows modifying the original map via the view wrapper:

import 'dart:collection';

void main() {
  var map = new Map.fromIterables(
    [1, 2, 3, 4], ['1', '2', '3', '4']);
  map[5] = '5';
  var unmodifiable = new UnmodifiableMapView(map);
  unmodifiable[6] = '6';
}

Any attempt to modify the collection throws a runtime exception as follows:

Unsupported operation: Cannot modify unmodifiable map
#0      MapView&&_UnmodifiableMapMixin.[]= (…)
#1      main (file:///…/bin/unmodifiable_map.dart:7:15)
…

The following diagram shows the class hierarchy of UnmodifiableMapView:

The unmodifiable map
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.116.51