monkey2 icon indicating copy to clipboard operation
monkey2 copied to clipboard

Feature request: Safe navigation operator for Null checking (MyObject?.SomeProperty )

Open Difference opened this issue 8 years ago • 4 comments

It would be nice to have the "Elvis" operator in MX2 to simplify property checking:

Current syntax examples: `If Myobject And Myobject.SomeNullableProperty

Local myVar:Float If Myobject myVar = Myobject.AFloatProperty`

New Syntax examples: `If Myobject?.SomeNullableProperty

Local myVar:= Myobject?.AFloatProperty`

Difference avatar Mar 01 '17 08:03 Difference

I have the same thought. :)

?. called "safe navigation operator", it do null checks for us and return null instead of throw an NullPointerException, https://en.wikipedia.org/wiki/Safe_navigation_operator Example:

Local name := article?.author?.name
If Not name Return

Elvis operator is ?:, it return right side only if left is null, (https://en.wikipedia.org/wiki/Elvis_operator) Example:

Local name := article?.author?.name
If Not name Return

Also there is a ?? useful operator to simplify ? .. Else construction (but not only), https://en.wikipedia.org/wiki/Null_coalescing_operator. Example:

Local title := customTitle ?? "Untitled"

Also I like the way Kotlin lang use ?: - we can write such code val city = getCityById(100500) ?: return assign value if it's not null or return - very short and readable. http://kotlinlang.org/docs/reference/null-safety.html#safe-calls

engor avatar Aug 30 '17 04:08 engor

I saw implementation for them in repo. Can't wait to try it out. :)

engor avatar Sep 22 '17 02:09 engor

Finished.

engor avatar Nov 08 '17 03:11 engor

Could be closed.

seyhajin avatar Jun 04 '19 10:06 seyhajin