Is there an “opposite” to the null coalescing operator? (…in any language?)

后端 未结 12 1071
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-04 18:38

null coalescing translates roughly to return x, unless it is null, in which case return y

I often need return null if x is null, otherwise return x

12条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 19:26

    There's the null-safe dereferencing operator (?.) in Groovy... I think that's what you're after.

    (It's also called the safe navigation operator.)

    For example:

    homePostcode = person?.homeAddress?.postcode
    

    This will give null if person, person.homeAddress or person.homeAddress.postcode is null.

    (This is now available in C# 6.0 but not in earlier versions)

提交回复
热议问题