given Nullable!T
assertEquals(some(7), toOptional([7])); assertEquals(none, toOptional([])); assertEquals(none, toOptional([null])); assertEquals(none, toOptional((int[]).init)); assertEquals(some(7), toOptional(Nullable!(int)(7))); assertEquals(none, toOptional(Nullable!(typeof(null))(null))); assertEquals(none, toOptional(Nullable!(int)()));
Optional!int foo; Optional!int bar; assertEquals(none, foo); foo = none; assertEquals(none, foo); foo = bar; assertEquals(none, bar); assertEquals(bar, foo); foo = 7; assertEquals(7, foo); // assign again to move instead of moveEmplace foo = 3; assertEquals(3, foo); foo = some(7); assertEquals(7, foo); // assign again to none invalidation defined value foo = none; assertEquals(none, foo);
auto arr = some([1, 2, 3, 45]); assertEquals(2, arr[1]); assertEquals([1, 2, 3, 45], arr[]); assertEquals([1, 2, 3, 45], arr[0 .. $]); auto jk = none!(int[]); assertEquals(none!int, jk[213]); assertEquals(none!(int[]), jk[]); assertEquals(none!(int[]), jk[0 .. $]);
Optional!int foo; assertEquals(0, foo.toHash); foo = 7; assertTrue(foo.toHash > 0); assertEquals(.hashOf(7), foo.toHash);
Optional!Object bar; assertEquals(0, bar.toHash); auto obj = new Object(); bar = obj; assertTrue(bar.toHash > 0); assertEquals(.hashOf(obj), bar.toHash);
auto obj = new Object(); Optional!Object bar = obj; assertEquals(typeid(Object).getHash(&obj), bar.toHash);
assertEquals(7, some(7)); assertEquals(none!int, none!int); assertEquals(none, none!int); assertEquals(none, none); assertEquals(none!int, some(none!int)); assertEquals(none, some(none)); // compare with nullable assertEquals(nullable(7), optional(7)); assertEquals(Nullable!(int).init, none!int); // range opEquals assertEquals([7], some(7)); int[] a = []; assertEquals(a, none!int);
@safe pure class C { int c; // assertEquals needs @safe and pure // toString method in case of fail @safe pure override string toString() const { import std.conv : to; return c.to!string; } } C c = new C(); assertEquals(c, optional(c)); assertEquals(optional(c), optional(c)); // cover toString method assertEquals("0", optional(c).front.toString);
assertEquals("Some(1)", some(1).toString); assertEquals("None", none.toString); assertEquals("Optional(None)", none!int.toString);
Converts a nullable type to an optional type