Null object: Difference between revisions

Content added Content deleted
(Add Ecstasy example)
(Replace println() with print(); replace output "syntaxhighlight" tag with "pre" tag)
Line 735: Line 735:
{
{
@Inject Console console;
@Inject Console console;
console.println($"Null value={Null}, Null.toString()={Null.toString()}");
console.print($"Null value={Null}, Null.toString()={Null.toString()}");


// String s = Null; // <-- compiler error: cannot assign Null to a String type
// String s = Null; // <-- compiler error: cannot assign Null to a String type
String? s = Null; // "String?" is shorthand for the union "Nullable|String"
String? s = Null; // "String?" is shorthand for the union "Nullable|String"
String s2 = "test";
String s2 = "test";
console.println($"s={s}, s2={s2}, (s==s2)={s==s2}");
console.print($"s={s}, s2={s2}, (s==s2)={s==s2}");


// Int len = s.size; // <-- compiler error: String? does not have a "size" property
// Int len = s.size; // <-- compiler error: String? does not have a "size" property
Int len = s?.size : 0;
Int len = s?.size : 0;
console.println($"len={len}");
console.print($"len={len}");


if (String test ?= s)
if (String test ?= s)
Line 755: Line 755:
}
}


// s2 = s; // <-- compiler error: a "String?" cannot be assigned to a "String"
// if (String test ?= s){} // <-- compiler error: The expression type is not nullable: "String"
s2 = s; // at this point, s is known to be a non-null String
if (String test ?= s)
console.print($"s={s}, s2={s2}, (s==s2)={s==s2}");
{
// the variable "test" is definitely assigned here
console.println($"test={test}");
}
else
{
// s2 = test; // <-- compiler error: "test" is not definitely assigned
}
}
}
}
}
</syntaxhighlight>
</syntaxhighlight>


{{out}}
Output:
<pre>
<syntaxhighlight>
Null value=Null, Null.toString()=Null
Null value=Null, Null.toString()=Null
s=Null, s2=test, (s==s2)=False
s=Null, s2=test, (s==s2)=False
len=0
len=0
test=a non-null value
s=a non-null value, s2=a non-null value, (s==s2)=True
</pre>
</syntaxhighlight>


=={{header|Eiffel}}==
=={{header|Eiffel}}==