Skip to main content

IsDefined

rascal-0.40.17

Synopsis

Assign but replace if value is not defined.

Description

First the value of Exp₁ is determined and if that is defined it is assigned to Assignable. Otherwise, the value of Exp₂ is assigned to Assignable.

Values which can be undefined are:

  • in Maps where the key is not set
  • values of Annotation which are not present.
  • values of Function's keyword parameters which have not been provided, but are set to default.
  • values of Constructor's keyword parameters which have not been provided, but are computed by defaults.

No other values can be used in an undefined state, so the ? operator does not make sense on undefined or uninitialized variables for example.

Examples

rascal>M = ("Andy": 1, "Brian" : 2);
map[str, int]: ("Andy":1,"Brian":2)

Using an isDefined assignable can we increment a non-existing entry:

rascal>M["SomebodyElse"] ? 0 += 1;
map[str, int]: ("Andy":1,"Brian":2,"SomebodyElse":1)
rascal>M["SomebodyElse"];
int: 1

And if we increment an existing entry the ? has no effect:

rascal>M["Andy"] ? 0 += 1;
map[str, int]: ("Andy":2,"Brian":2,"SomebodyElse":1)
rascal>M["Andy"]
int: 2

Benefits

  • short notation that inline initialization of map values, keyword fields or annotations without having to write a lot of boilerplate if-then-else statements.