Skip to contents

Binary operator to simplify null expressions

Usage

x %??% y

Arguments

x

A value that is possible NULL

y

A value that is not NULL

Value

Returns the value of the left hand side (LHS) if it is not null, else returns the value of the right hand side (RHS) that may be NULL.

Details

The objective of the null coalescing operator is to simplify the expression:

if(is.null(x)) {
  y
else {
  x
}

This allows it to be readable inline.

Warning

Due to the way objects are created within R, the NULL value is not able to be stored within atomic vectors. However, the NULL value can be stored within a list. This operator will not be triggered if NULL is within a list! That is, the RHS side will be returned.

See also

Examples

# Null value
x <- NULL

# Before
y <- if(is.null(x)){ "Unset" } else { x }

# After
y <- x %??% "Unset"

# Concrete examples without variables
# Returns 3 as the LHS is _not_ NULL
3 %??% 4
#> [1] 3

# Returns 1 as the LHS is _not_ NULL
1 %??% NULL
#> [1] 1

# Returns 2 as the LHS is NULL
NULL %??% 2
#> [1] 2

# Coalesce operator
NULL %??% NULL %??% 5
#> [1] 5

# Coalesce operator
NULL %??% 7 %??% 8
#> [1] 7