Feedback on nulls in switch
Mark Staller
mark.staller at gmx.net
Tue Aug 11 00:50:47 UTC 2020
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