Null coalescing operator From Wikipedia, the free encyclopedia

The coalescing operator (called the Logical Defined-Or operator in , Elvis- operator in Groovy[1] and Kotlin[2]) is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, including #,[3] Perl as of version 5.10,[4] and Swift.[5]

In contrast to the ternary conditional if operator used as x ? x : y, the is a binary operator and thus evaluates its operands at most once, which is significant if the evaluation of x has side-effects.

Contents

1 C# 2 CFML 3 4 F# 5 Perl 6 Swift 7 SQL 8 PHP 8.1 ?: operator 8.2 ?? operator 9 Python 10 Scheme 11 JavaScript 12 Kotlin 13 Groovy 14 Objective-C 15 Haskell 16 See also 17 References

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,[6] Railo 4.1,[7] 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.[8] 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:[9] 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.

Unlike C, in Perl the boolean or expression a || b returns a if it is not only non- null but also not false (i.e. not 0 nor the empty string) or else b. Still, this subtle difference from the "//" operator means that the "||" operator is not a null coalescing operator, e.g.

DB<1> print 0 // 1 # A null coalescing operator 0 DB<2> print 0 || 1 # Not a null coalescing operator 1

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,[10] SQL Server,[11] PostgreSQL,[12] SQLite[13] and MySQL.[14] 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

?: operator

In PHP (starting with version 5.3), it has been possible to leave out the middle part of the ?: conditional operator, which is also used as a ternary operator, to create a binary operator. Since it first appeared in related languages,[15][16] this has been known as the due to its resemblance to an emoticon.[17][18]

$foo = $foo ? $foo : $bar;

$foo = $foo ?: $bar;

This also allows one to easily return a value with less chance of throwing an error if the value is null or undefined: return $foo ?: $bar;

While this is popular for concise expressions, due to an unfortunate error in the language grammar of PHP, Elvis operators are subject to the same syntax limitations when chained together, as it is considered to be a ternary operator "short-cut".[19] The ternary conditional operator is left-associative in PHP, which is the opposite of the expected behavior; so combining several conditional operators may produce extremely non-intuitive results:[20]

$var = $foo ? $bar : $bar ?: $baz; # is equivalent to:

$var = ($foo ? $bar : $bar) ?: $baz; $var = $bar ?: $baz

# The expected behavior must be specified with parentheses.

$var = $foo ? $bar : ($bar ?: $baz);

It can also be used to echo or return the resulting value instead of assigning it to a variable, as with use of the ternary operator in PHP: echo $foo ?: $bar; return $foo ?: $bar;

Note that, like some others, ?: is not a true null coalescing operator, as it returns the first argument if it evaluates to TRUE in PHP. This is used for loose typing of expressions.

?? operator

PHP 7 will add[21] a true 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:

$var = $foo ?? $bar ?? $foobar; // equivalent to: $var = (isset($foo) ? $foo : (isset($bar) ? $bar : $foobar));

Python

Python's "or" operator is not a null coalescing operator, as demonstrated below:

>>> 0 or 1 1

If or were a null coalescing operator, it would return the first non-null argument, which is 0. (0 and null, called None in Python, are distinct concepts.) In practice, however, the or operator is sometimes used for this purpose when the left operand is guaranteed not to be 0, False or (empty-string) (or when distinguishing them from None is not important). 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.

JavaScript

In JavaScript, null coalescing can be accomplished through the use of a boolean "or" statement: function setTitle(suppliedTitle) { this.title = suppliedTitle || "Default title"; }

Note that this is not a true example of null coalescing due to JavaScript's concept of "truthiness." Because of this, values that JavaScript evaluates as false (such as 0 or false) will also be coalesced in the evaluation of the statement, possibly yielding undesirable results. Kotlin

Kotlin uses the '?:' operator.[2] val title = suppliedTitle ?: "Default title"

Groovy

Groovy uses the '?:' operator, referred to as the "Elvis Operator" in the language documentation.[1] def title = suppliedTitle ?: "Default Title"

Objective-C

In Objective-C, null coalescing is achieved by simply omitting the otherwise duplicate variable after the ? in the ?: operator: id valueOrNil = ...; id nonNilValue = valueOrNil ?: @"Some Default Value";

Note: As is the case with Javascript and Python, this is not "true" null coalescing, since if you were to use primitive value like int or BOOL, they will evaluate to false, returning the trailing value. Also note that this syntax is a GNU extension to C added in the LLVM compiler. 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[22] 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) Operator (programming) References

1. "Operators - Groovy" (http://docs.codehaus.org/display/GROOVY/Operators#Operators- ElvisOperator%28%3F%3A%29). 2. "Null Safety" (http://kotlinlang.org/docs/reference/null-safety.html). 3. ?? Operator (C# Reference) (http://msdn.microsoft.com/en-us/library/ms173224.aspx) 4. // Operator (Perl Reference) (http://perldoc.perl.org/perlop.html#C-style-Logical-Defined- Or) 5. Nil Coalescing Operator (https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_ Programming_Language/BasicOperators.html#//apple_ref/doc/uid/TP40014097-CH6- XID_124) 6. Elvis operator (https://wikidocs.adobe.com/wiki/display/coldfusionen/Elvis+operator) 7. RAILO-2195 and (https://issues.jboss.org/browse/RAILO-2195) Lucee 4.5 add support for the Elvis Operator 8. Null Values (F# Reference) (http://msdn.microsoft.com/en-us/library/dd233197.aspx) 9. Operator Overloading (F# Reference) (http://msdn.microsoft.com/en- us/library/dd233204.aspx) 10. http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions023.htm#SQLRF00617 11. http://technet.microsoft.com/en-us/library/ms174075.aspx 12. http://www.postgresql.org/docs/9.1/static/functions-conditional.html#FUNCTIONS- COALESCE-NVL-IFNULL 13. http://www.sqlite.org/lang_corefunc.html 14. http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#function_coalesce 15. "coding style - ?: operator PHP" (http://stackoverflow.com/questions/1993409/operator- ). Retrieved 2014-02-17. 16. https://github.com/getrailo/railo/wiki/Operators#elvis-operator 17. "coding style - ?: operator" (http://stackoverflow.com/questions/1993409/operator-php). Stack Overflow. Retrieved 2014-02-17. Lay summary (http://i.stack.imgur.com/hQlrp.png) – elvis emoticon graphic. 18. Joyce Farrell. Java Programming. p. 276. ISBN 978-1285081953. "The new operator is called Elvis operator because it uses a and a colo together (?:)" 19. "PHP Bug #61915: incorrect associativity of ternary operator" (https://bugs.php.net/bug.php?id=61915). PHP website. 2012-05-02. Retrieved 2014-02-17. 20. "Comparison Operators, Example #3" (http://php.net/ternary#example-121). PHP website. Retrieved 2014-02-17. 21. "PHP: rfc:isset_ternary" (https://wiki.php.net/rfc/isset_ternary). Retrieved 16 December 2014. 22. "Hackage" (http://hackage.haskell.org/package/base-4.8.0.0/docs/Prelude.html#t:Maybe). Retrieved 10 July 2015.

Retrieved from "https://en.wikipedia.org/w/index.php? title=Null_coalescing_operator&oldid=670832547"

Categories: Conditional constructs Operators (programming) Binary operations This page was last modified on 10 July 2015, at 14:24. Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization.