I propose the following syntaxes:
val ?? default
for val === nothing ? val : default
val ?= default
for val === nothing ? val : (val = default)
d[key] ?? default
for get(()->default, d, key)
d[key] ?= default
for get!(()->default, d, key)
+1, but I think there are two secondary questions to address:
missing
be supported too (coalesce
handles both nothing
and missing
)Some
values be unwrapped (coalesce
does, and that's what languages with a Nullable
type do)While we're at it, I'll mention that some languages like Kotlin use val!!
to assert that val !== nothing
, equivalent to the unexported notnothing
helper (can be used to unwrap Some
too); Swift and TypeScript use a single !
for that, but obviously it's not possible in Julia. Some languages like Swift and Kotlin also allow val?.field
as a shorthand for val === nothing ? nothing : val.field
, and col?[i]
for col === nothing ? nothing : col[i]
. We might want to ensure this syntax is available in case we want to support it at some point.
We could potentially make prefix !!x
an operator. This is a useless thing to do currently since !x
is an error unless x
is one of true
, false
or missing
and !!x
is the identity on all of those values. In order to make that non-breaking, we might want to make it an error now (or at least document that it might change). Of course, if we make !!x
mean x === nothing ? error() : nothing
then that would actually not be a breaking change since any code that worked before would still work.
Isn't there a typo in the OP with ===
instead of !==
, and also would it be x === nothing ? error() : x
for x!!
?
Yes, I got the order wrong in the ternary.
I have just found this issue. My opinion is that if we implement ??
(which I support) we then can update coalesce
then to avoid issues described in #26927.
Most helpful comment
+1, but I think there are two secondary questions to address:
missing
be supported too (coalesce
handles bothnothing
andmissing
)Some
values be unwrapped (coalesce
does, and that's what languages with aNullable
type do)While we're at it, I'll mention that some languages like Kotlin use
val!!
to assert thatval !== nothing
, equivalent to the unexportednotnothing
helper (can be used to unwrapSome
too); Swift and TypeScript use a single!
for that, but obviously it's not possible in Julia. Some languages like Swift and Kotlin also allowval?.field
as a shorthand forval === nothing ? nothing : val.field
, andcol?[i]
forcol === nothing ? nothing : col[i]
. We might want to ensure this syntax is available in case we want to support it at some point.