Null coalescing operatorThe null coalescing operator is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, such as (in alphabetical order): C#[1] since version 2.0,[2] Dart[3] since version 1.12.0,[4] PHP since version 7.0.0,[5] Perl since version 5.10 as logical defined-or,[6] PowerShell since 7.0.0,[7] and Swift[8] as nil-coalescing operator. It is most commonly written as While its behavior differs between implementations, the null coalescing operator generally returns the result of its left-most operand if it exists and is not null, and otherwise returns the right-most operand. This behavior allows a default value to be defined for cases where a more specific value is not available. Like the binary Elvis operator, usually written as Examples by languagesBourne-like shellsIn Bourne shell (and derivatives), "If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted":[9] #supplied_title='supplied title' # Uncomment this line to use the supplied title
title=${supplied_title:-'Default title'}
echo "$title" # prints: Default title
C#In C#, the null coalescing operator is It is most often used to simplify 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 result in the same value being stored into the variable named
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. If, for example, a variable should be changed to another value if its value evaluates to null, since C# 8.0 the some_Value ??= some_Value2;
Which is a more concise version of: some_Value = some_Value ?? some_Value2;
In combination with the null-conditional operator string pageTitle = page?.Title ?? "Default Title";
CFMLAs of ColdFusion 11,[10] Railo 4.1,[11] CFML supports the null coalescing operator as a variation of the ternary operator, possiblyNullValue ?: valueIfNull
FreemarkerMissing values in Apache FreeMarker will normally cause exceptions. However, both missing and null values can be handled, with an optional default value:[12] ${missingVariable!"defaultValue"}
or, to leave the output blank: ${missingVariable!}
JavaScriptJavaScript's nearest operator is In the following example, const a = b ?? 3;
Before the nullish coalescing operator, programmers would use the logical OR operator ( In the following example, const a = b || 3;
KotlinKotlin uses the val title = suppliedTitle ?: "Default title"
Objective-CIn Obj-C, the nil coalescing operator is id value = valueThatMightBeNil ?: valueIfNil;
This is the same as writing id value = valueThatMightBeNil ? valueThatMightBeNil : valueIfNil;
PerlIn Perl (starting with version 5.10), the operator is $possibly_null_value // $value_if_null
The possibly_null_value is evaluated as null or not-null (in Perl terminology, 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 ( 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 $a //= $b
is largely equivalent to: $a = $a // $b
This operator differs from Perl's older $a = 0;
$b = 1;
$c = $a // $b; # $c = 0
$c = $a || $b; # $c = 1
PHPPHP 7.0 introduced[15] a null-coalescing operator with the $name = $request->input['name'] ?? $request->query['name'] ?? 'default name';
/* Equivalent to */
if (isset($request->input['name'])) {
$name = $request->input['name'];
} elseif (isset($request->query['name'])) {
$name = $request->query['name'];
} else {
$name = 'default name';
}
$user = $this->getUser() ?? $this->createGuestUser();
/* Equivalent to */
$user = $this->getUser();
if ($user === null) {
$user = $this->createGuestUser();
}
$pageTitle = $title ?? 'Default Title';
/* Equivalent to */
$pageTitle = isset($title) ? $title : 'Default Title';
Version 7.4 of PHP introduced the Null Coalescing Assignment Operator with the // The following lines are doing the same
$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';
// Instead of repeating variables with long names, the equal coalesce operator is used
$this->request->data['comments']['user_id'] ??= 'value';
PowerShellSince PowerShell 7, the $myVar = $null
$x = $myVar ?? "something" # assigns "something"
RSince R version 4.4.0 the > NULL %||% 2
[1] 2
RustWhile there's no
// Option
// An Option can be either Some(value) or None
Some(1).unwrap_or(0); // evaluates to 1
None.unwrap_or(0); // evaluates to 0
None.unwrap_or_else(get_default); // evaluates to the result of calling the function get_default
// Result
// A Result can be either Ok(value) or Err(error)
Ok(1).unwrap_or(0); // evaluates to 1
Err("oh no").unwrap_or(1); // evaluates to 1
SQLIn 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,[18] SQL Server,[19] PostgreSQL,[20] SQLite[21] and MySQL.[22] 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, ...]);
The difference between ISNULL and COALESCE is that the type returned by ISNULL is the type of the leftmost value while COALESCE returns the type of the first non-null value. SwiftIn Swift, the nil coalescing operator is 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";
See also
References
|
Portal di Ensiklopedia Dunia