On 03/06/2012 12:19 PM, Timon Gehr wrote:
On 03/06/2012 04:46 PM, foobar wrote:
On Tuesday, 6 March 2012 at 10:19:19 UTC, Timon Gehr wrote:
This is quite close, but real support for non-nullable types means
that they are the default and checked statically, ideally using data
flow analysis.
I agree that non-nullable types should be made the default and
statically checked but data flow analysis here is redundant.
consider:
T foo = ..; // T is not-nullable
T? bar = ..; // T? is nullable
bar = foo; // legal implicit coercion T -> T?
foo = bar; // compile-time type mismatch error
//correct way:
if (bar) { // make sure bar isn't null
// compiler knows that cast(T)bar is safe
foo = bar;
}
Right. This example already demonstrates some simplistic data flow
analysis.
of course we can employ additional syntax sugar such as:
foo = bar || <default_value>;
furthermore:
foo.method(); // legal
bar.method(); // compile-time error
it's all easily implementable in the type system.
Actually it requires some thinking because making initialization of
non-null fields safe is not entirely trivial.
For example:
http://pm.inf.ethz.ch/publications/getpdf.php/bibname/Own/id/SummersMuellerTR11.pdf
CTFE and static constructors solve that issue for static data.
I can't seem to download the PDF... it always gives me just two bytes.
But to initialize non-null fields, I suspect we would need to be able to
do stuff like this:
class Foo
{
int dummy;
}
class Bar
{
Foo foo = new Foo();
this() { foo.dummy = 5; }
}
Which would be lowered by the compiler into this:
class Bar
{
// Assume we've already checked for bogus assignments.
// It is now safe to make this nullable.
Nullable!(Foo) foo;
this()
{
// Member initialization is done first.
foo = new Foo();
// Then programmer-supplied ctor code runs after.
foo.dummy = 5;
}
}
I remember C# being able to do this. I never understood why D doesn't
allow this. Without it, I have to repeat myself a lot, and that is just
wrong ;). Allowing this kind of initialization might also make it
possible for us to have zero-argument struct constructors.