Optional types

Friday, January 1, 2010
In a response to my previous post, Guido suggested that I introduce an "optional" keyword to indicate that a reference type can be Null. I've gone ahead and implemented this, and here's a unit test to prove it:

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.)

0 comments:

Post a Comment