Non-nullable references, again
Daniel Keep
daniel.keep.lists at gmail.com
Wed Dec 31 18:50:53 PST 2008
Benji Smith wrote:
> Don wrote:
>> Denis Koroskin wrote:
>>> Foo nonNull = new Foo();
>>> Foo? possiblyNull = null;
> >
>> Wouldn't this cause ambiguity with the "?:" operator?
>
> At first, thought you might be right, and that there would some
> ambiguity calling constructors of nullable classes (especially given
> optional parentheses).
>
> But for the life of me, I couldn't come up with a truly ambiguous
> example, that couldn't be resolved with an extra token or two of lookahead.
>
> The '?' nullable-type operator is only used in type declarations, not
> in expressions, and the '?:' operator always consumes a few trailing
> expressions.
>
> Also (at least in C#) the null-coalesce operator (which converts
> nullable objects to either a non-null instance or a default value) looks
> like this:
>
> MyClass? myNullableObj = getNullableFromSomewhere();
> MyClass myNonNullObj = myNullableObj ?? DEFAULT_VALUE;
>
> Since the double-hook is a single token, it's also unambiguous to parse.
>
> --benji
Disclaimer: I'm not an expert on compilers. Plus, I just got up. :P
The key is that the parser has to know what "MyClass" means before it
can figure out what the "?" is for; that's why it's context-dependant.
D avoids this dependency between compilation stages, because it
complicates the compiler. When the parser sees "MyClass", it *doesn't
know* that it's a type, so it can't distinguish between a nullable type
and an invalid ?: expression.
At least, I think that's how it works; someone feel free to correct me
if it's not. :P
-- Daniel
More information about the Digitalmars-d
mailing list