Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe navigation operator (&.) for nil

As Ruby 2.3 introduces the Safe navigation operator(&.), a.k.a lonely operator, the behavior on nil object seems odd.

nil.nil?    # => true nil&.nil?   # => nil 

Is that designed to behave like this way? Or some edge case that slipped away when adding the lonely operator?

like image 429
sbs Avatar asked Jan 04 '16 00:01

sbs


People also ask

What is the purpose of the safe navigation operator?

In programming languages where the navigation operator (e.g. ".") leads to an error if applied to a null object, the safe navigation operator stops the evaluation of a method/field chain and returns null as the value of the chain expression.

What is safe navigation operator in angular?

The Angular safe navigation operator, ? , guards against null and undefined values in property paths. Here, it protects against a view render failure if item is null .

Is null in Apex?

As a strongly typed language and derived from mainstream object-oriented languages such as Java or C#, Apex inherited a certain feature – the null value. Thus, we can read in the documentation that: All Apex types are implicitly nullable and can hold a null value returned from the operator.

Is and null the same in Apex?

Hi Shilpa, null and '' operator seems similar but there is a slight difference between these. If you want to check that a string is empty then you can go with ' ' but when you need to check with refernces like ID and collections then you have to use null.


2 Answers

foo&.bar is shorthand for foo && foo.bar, so what would you expect the result of the expression nil && nil.nil? to be?

like image 195
mwp Avatar answered Sep 28 '22 11:09

mwp


This is because nil&.nil? is shorthand for nil && nil.nil?. This would evaluate to nil && true, which is then nil.

(nil && x).nil? always evaluates to true, for any value of x.

While the syntax has power, this specific case has some potential to become a 'gotcha' for a developer:

(stuff&.things).nil? => This produces true if stuff doesn't exist, or stuff.things returns nil.

vs. the below case:

stuff&.things&.nil? => This produces nil in every case except the case where stuff.things returns something other than nil, in which case it would return false.

Because of the difficulty in normal boolean logic of differentiating between false and nil, it is unlikely that this would make sense in normal logic.

like image 24
Oeste Avatar answered Sep 28 '22 12:09

Oeste