new conditional type to test for non-null
Submitted by Allison (desrt)
Link to original bug (#643643)
Description
We've long discussed the possibility of adding a new kind of conditional to the language that executes a block of code when a particular expresion is non-NULL.
The essential features that I would insist on are as follows:
-
can be based on any expression with a nullable type (or not)
-
is syntactically slim
-
allows introduction of a new block
-
creates a new variable that has its scope limited to the block
-
the type of the new variable is non-nullable
I consider the feature that the new variable is non-nullable to be one of the most important. I hope that one day it's a lot easier to write natural-looking Vala code that compiles with the nullnazi enabled (without having (!) all over the place).
I imagine it to look something like this:
when (var button = widget as Gtk.Button) {
....
} else when (var label = widget as Gtk.Label) {
....
} else {
....
}
or
if (var button from widget as Gtk.Button) {
....
} else {
....
}
or similar.
This has uses other than making downcasting nicer. For example, it could be used as an alternative to this sort of code:
{
...
{
var file = open_file(); // variable inside block to limit scope
...
} // file is closed here
...
}
And really has a lot of usefulness in any case that we want to check for the possibility of NULL on an expression while assigning it to a variable (which is insanely common).
We could also imagine a strange variant of it that looks like this:
{
MyClass? x = get_instance_or_null ();
when (x) {
// here, 'x' is of non-nullable type 'MyClass'
} else {
// here, 'x' is not in scope
}
}
which is basically just a shortcut of when (var x = x).