def testOptionalType {var x:optional String;// Accessing x.length is OK since x is a string.x = "Hello";assertEq(5, x.length);// However, x.length throws an exception when x is null.x = null;try {assertEq(5, x.length);fail("union member test failed");} catch t:TypecastException {}}
The way that optional types (which are really just type unions with 'Null') work is that any attempt to dereference the type inserts a null pointer check. This throws as typecast exception (the reason is that 'Null' is considered a type.)
No comments:
Post a Comment