Null coalescing operator
The null coalescing operator (called the Logical Defined-Or operator in Perl) is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, including C#,[1] Perl as of version 5.10,[2] Swift,[3] and PHP 7.0.0.[4]
In contrast to the ternary conditional if operator used as x ? x : y
, but like the binary Elvis operator used as x ?: y
, the null coalescing operator is a binary operator and thus evaluates its operands at most once, which is significant if the evaluation of x
has side-effects.
C#
In C#, the null coalescing operator is ??
. It is most often used to simplify null expressions as follows:
possiblyNullValue ?? valueIfNull
For example, if one wishes to implement some C# code to give a page a default title if none is present, one may use the following statement:
string pageTitle = suppliedTitle ?? "Default Title";
instead of the more verbose
string pageTitle = (suppliedTitle != null) ? suppliedTitle : "Default Title";
or
string pageTitle;
if (suppliedTitle != null)
pageTitle = suppliedTitle;
else
pageTitle = "Default Title";
The three forms are logically equivalent.
The operator can also be used multiple times in the same expression:
return some_Value ?? some_Value2 ?? some_Value3;
Once a non-null value is assigned to number, or it reaches the final value (which may or may not be null), the expression is completed.
CFML
As of ColdFusion 11,[5] Railo 4.1,[6] CFML supports the null coalescing operator as a variation of the ternary operator, ?:
. It is functionally and syntactically equivalent to its C# counterpart, above. Example:
possiblyNullValue ?: valueIfNull
Clojure
Clojure's or macro works similarly.
(or page-title "Default title")
You can also chain values.
(or x y z) ;; returns first not-nil value or nil
F#
The null value is not normally used in F# for values or variables.[7] However null values can appear for example when F# code is called from C#.
F# does not have a built-in null coalescing operator but one can be defined as required as a custom operator:[8]
let (|?) lhs rhs = (if lhs = null then rhs else lhs)
This custom operator can then be applied as per C#'s built-in null coalescing operator:
let pageTitle = suppliedTitle |? "Default Title"
Perl
In Perl (starting with version 5.10), the operator is //
and the equivalent Perl code is:
$possibly_null_value // $value_if_null
The possibly_null_value is evaluated as null or not-null (or, in Perl, undefined or defined). On the basis of the evaluation, the expression returns either value_if_null when possibly_null_value is null, or possibly_null_value otherwise. In the absence of side-effects this is similar to the way ternary operators (?:
statements) work in languages that support them. The above Perl code is equivalent to the use of the ternary operator below:
defined($possibly_null_value) ? $possibly_null_value : $value_if_null
This operator's most common usage is to minimize the amount of code used for a simple null check.
Perl additionally has a //=
assignment operator, where
a //= b
is largely equivalent to:
a = a // b
Swift
In Swift, the nil coalescing operator is ??
. It is used to provide a default when unwrapping an optional type:
optionalValue ?? valueIfNil
For example, if one wishes to implement some Swift code to give a page a default title if none is present, one may use the following statement:
var suppliedTitle: String? = ...
var pageTitle: String = suppliedTitle ?? "Default Title"
instead of the more verbose
var pageTitle: String = (suppliedTitle != nil) ? suppliedTitle! : "Default Title";
SQL
In Oracle's PL/SQL, the NVL() function provides the same outcome:
NVL(possibly_null_value, 'value if null');
In SQL Server/Transact-SQL there is the ISNULL function that follows the same prototype pattern:
ISNULL(possibly_null_value, 'value if null');
Attention should be taken to not confuse ISNULL with IS NULL – the latter serves to evaluate whether some contents are defined to be NULL or not.
The ANSI SQL-92 standard includes the COALESCE function implemented in Oracle,[9] SQL Server,[10] PostgreSQL,[11] SQLite[12] and MySQL.[13] The COALESCE function returns the first argument that is not null. If all terms are null, returns null.
COALESCE(possibly_null_value[, possibly_null_value, ...]);
PHP
PHP 7 has introduced[14] a null-coalescing operator with the ??
syntax. This checks strictly for NULL or a non-existent variable/array index/property. In this respect, it acts similarly to PHP's isset()
pseudo-function:
$quux = $_POST['quux'] ?? $_GET['quux'] ?? $quuxDefault;
// Equivalent to:
if (isset($_POST['quux'])) {
$quux = $_POST['quux'];
} elseif (isset($_GET['quux'])) {
$quux = $_GET['quux'];
} else {
$quux = $quuxDefault;
}
$pageTitle = $suppliedTitle ?? 'Default Title';
// Equivalent to:
$pageTitle = (isset($suppliedTitle) ? $suppliedTitle : 'Default Title');
Scheme
In Scheme, "boolean false" and "null" are represented by the same value, written as #f. Furthermore, #f is the only value in Scheme that is treated as false by boolean operators, unlike some other languages, in which values like 0, the empty string, and the empty list may function as false. The boolean 'or' operation, written as (or x y), returns x if it is not false, otherwise it returns y. Thus, in Scheme, there is no need for a separate "null coalescing operator", because the or operator serves that purpose.
Kotlin
Kotlin uses the '?:' operator.[15] This is an unusual choice of symbol, given that ?: is typically used for the Elvis operator, not null coalescing.
val title = suppliedTitle ?: "Default title"
Haskell
Types in Haskell can in general not be null. Representation of computations that may or may not return a meaningful result is represented by the generic Maybe type, defined in the standard library[16] as
data Maybe a = Nothing | Just a
The null coalescing operator replaces null pointers with a default value. The haskell equivalent is a way of extracting a value from a Maybe by supplying a default value. This is the function fromMaybe.
fromMaybe :: a -> Maybe a -> a
fromMaybe d x = case x of {Nothing -> d;Just v -> v}
Some example usage follows.
fromMaybe 0 (Just 3) -- returns 3
fromMaybe "" (Nothing) -- returns ""
See also
- ?: (conditional)
- Elvis operator (binary ?:)
- Operator (programming)
References
- ↑ ?? Operator (C# Reference)
- ↑ // Operator (Perl Reference)
- ↑ Nil Coalescing Operator
- ↑ PHP 7.0.0 RC 7 Released
- ↑ Elvis operator
- ↑ RAILO-2195 and Lucee 4.5 add support for the Elvis Operator
- ↑ Null Values (F# Reference)
- ↑ Operator Overloading (F# Reference)
- ↑ http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions023.htm#SQLRF00617
- ↑ http://technet.microsoft.com/en-us/library/ms174075.aspx
- ↑ http://www.postgresql.org/docs/9.1/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL
- ↑ http://www.sqlite.org/lang_corefunc.html
- ↑ http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#function_coalesce
- ↑ "PHP: rfc:isset_ternary". Retrieved 16 December 2014.
- ↑ "Null safety"..
- ↑ "Hackage". Retrieved 10 July 2015.