RosettaCodeData/Task/Null-object/Ecstasy/null-object.ecstasy

26 lines
965 B
Plaintext

module NullObject {
void run() {
@Inject Console console;
console.print($"Null value={Null}, Null.toString()={Null.toString()}");
// String s = Null; // <-- compiler error: cannot assign Null to a String type
String? s = Null; // "String?" is shorthand for the union "Nullable|String"
String s2 = "test";
console.print($"{s=}, {s2=}, {s==s2=}");
// Int len = s.size; // <-- compiler error: String? does not have a "size" property
Int len = s?.size : 0;
console.print($"{len=}");
if (String test ?= s) {
// "s" is still Null in this test, we never get here
} else {
s = "a non-null value";
}
// if (String test ?= s){} // <-- compiler error: The expression type is not nullable
s2 = s; // at this point, s is known to be a non-null String
console.print($"{s=}, {s2=}, {s==s2=}");
}
}