Navigation
Synopsis Test whether expression has a defined value, otherwise provide alternative.
Syntax Exp1 ? Exp2
Types
Exp1 Exp2 Exp1 ? Exp2
T1 T2 T2 <: T1
Description If no exception is generated during the evaluation of Exp1, the result of Exp1 ? Exp2 is the value of Exp1. Otherwise, it is the value of Exp2.

Also see isDefined and Assignment.
Examples This test can, for instance, be used to handle the case that a certain key value is not in a map:
rascal>T = ("a" : 1, "b" : 2);
map[str, int]: ("a":1,"b":2)
Trying to access the key "c" will result in an error:
rascal>T["c"];
|stdin:///|(2,3,<1,2>,<1,5>): NoSuchKey("c")
	at ___SCREEN_INSTANCE___(|stdin:///|(0,7,<1,0>,<1,7>))


Using the ? operator, we can write:
rascal>T["c"] ? 0;
int: 0
This is very useful, if we want to modify the associated value, but are not sure whether it exists:
rascal>T["c"] ? 0 += 1;
map[str, int]: ("a":1,"b":2,"c":1)
Another example using a list:
rascal>L = [10, 20, 30];
list[int]: [10,20,30]
rascal>L[4] ? 0;
int: 0
It is, however, not possible to assign to index positions outside the list.
Is this page unclear, or have you spotted an error? Please add a comment below and help us to improve it. For all other questions and remarks, visit ask.rascal-mpl.org.