Feedback on nulls in switch
Christian Beikov
christian.beikov at gmail.com
Tue Aug 11 06:34:42 UTC 2020
What happened to the question mark syntax proposal for representing
nullable variable types? It looks like this would work here since we are
in a default-non-null context, even when using the "var" keyword and at
the same time be more explicit for the reader. Here an example:
switch (a) {
case Box(var?b): // We are here if `a instanceof Box`.
// `b` can be `null`
case Integer i: // We are here if `a instanceof Integer`.
// `i` can't be `null`
case Object? o: // We are here if `a instanceof Object`.
// `o` can be `null`
}
Regards,
Christian
Am 11.08.2020 um 02:50 schrieb Mark Staller:
> Just throwing in my 2 cents on how I would expect `switch` to work with
> pattern matching.
>
> #1
> switch (a) { // <- NPE in case of `a == null`
>
> case Box(_type_or_var_ b): // We are here if `a instanceof Box`.
> // `b` can be `null`
>
> case Integer i: // We are here if `a instanceof Integer`.
> // `i` can't be `null`
>
> case Object o: // We are here if `a instanceof Object`.
> // `o` can't be `null`
> }
>
> #2
> switch (a) { // <- NPE in case of `a == null`
>
> case Box(_type_or_var_ b): // We are here if `a instanceof Box`.
> // `b` can be `null`
>
> case Integer i: // We are here if `a instanceof Integer`.
> // `i` can't be `null`
>
> case Object o: // We are here if `a instanceof Object`.
> //`o` can't be `null`
>
> default: // All other cases
> }
>
> #3
> switch (a) { // <- No NPE in case of `a == null`
>
> case null: // We are here if `a == null`
>
> case Integer i: // We are here if `a instanceof Integer`.
> // `i` can't be `null`
>
> case Box(_type_or_var_ b): // We are here if `a instanceof Box`.
> // `b` can be `null`
>
> case Object o: // We are here if `a instanceof Object`.
> // `o` can't be `null`
> }
>
> #4
> switch (a) { // <- No NPE in case of `a == null`
>
> case null: // We are here if `a == null`
>
> case Box(_type_or_var_ b): // We are here if `a instanceof Box`.
> // `b` can be `null`
>
> case Integer i: // We are here if `a instanceof Integer`.
> // `i` can't be `null`
>
> case Object o: // We are here if `a instanceof Object`.
> // `o` can't be `null`
>
> default: // All other cases
> }
>
> #1 and #2 keep the legacy behavior and compatibility.
> Any `switch` that has a `case null:` does not throw NPE (signaling "new
> null-friendly switch mode", kind of like how `->` signaled new
> expression switch).
> `default` does not catch nulls (this is debatable instead of `case
> null:` if legacy behavior doesn't matter).
> Deconstruction patterns are kept null agnostic, no matter if Box(var
> b)/Box(Object b)/...
>
> Mark
More information about the amber-dev
mailing list