Skip to main content

Boolean IfDefinedElse



Test whether expression has a defined value, otherwise provide alternative.


Exp₁ ? Exp₂



Exp₁Exp₂Exp₁ ? Exp₂
T₁T₂T₂ <: T₁


If no exception is generated during the evaluation of Exp₁, the result of Exp₁ ? Exp₂ is the value of Exp₁. Otherwise, it is the value of Exp₂.

Also see IsDefined and Assignment.


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:

|prompt:///|(2,3,<1,2>,<1,5>): NoSuchKey("c")
at $shell$(|prompt:///|(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.