Skip to content
This repository was archived by the owner on Mar 24, 2021. It is now read-only.

Make Optional implement Iterable #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/optional.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@

library quiver.optional;

import 'dart:collection';

/// A value that might be absent.
///
/// Use Optional as an alternative to allowing fields, parameters or return
/// values to be null. It signals that a value is not required and provides
/// convenience methods for dealing with the absent case.
class Optional<T> {
class Optional<T> extends IterableBase<T> {
final T _value;

/// Constructs an empty Optional.
Expand Down Expand Up @@ -90,6 +92,10 @@ class Optional<T> {
: new Optional.of(transformer(_value));
}

@override
Iterator<T> get iterator =>
isPresent ? <T>[_value].iterator : new Iterable<T>.empty().iterator;

/// Delegates to the underlying [value] hashCode.
int get hashCode => _value.hashCode;

Expand Down
17 changes: 17 additions & 0 deletions test/optional_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -110,5 +110,22 @@ main() {
expect(new Optional<int>.fromNullable(null).toString(),
equals('Optional { absent }'));
});

test('length when absent should return 0', () {
expect(const Optional.absent().length, equals(0));
});

test('length when present should return 1', () {
expect(new Optional<int>.of(1).length, equals(1));
});

test('expand should behave as equivalent iterable', () {
final optionals = <Optional<int>>[
new Optional<int>.of(1),
const Optional.absent(),
new Optional<int>.of(2)
].expand((i) => i);
expect(optionals, orderedEquals([1, 2]));
});
});
}