Another cool addition of JEP 406 is its support for handling `null` in switches. You know how you need to do `null`-check before `switch` if you can't be sure and want to prevent an NPE? That's a future thing of the past! 🧵 1/5
Another cool addition of JEP 406 is its support for handling `null` in switches. You know how you need to do `null`-check before `switch` if you can't be sure and want to prevent an NPE? That's a future thing of the past! 🧵 1/5 https://t.co/kVy3YG4bvv
From #Java17 on, a switch's case label can include `null`, e.g. `case null -> ...`. If the switched-over variable is `null` and such a label exists, the corresponding branch gets executed. If it doesn't exist, an NPE is thrown as before. 2/5
We could discuss whether it would be nice if the `default` label covered the `null` case (that would mix error handling and "other cases" handling by default, though), but that's not gonna happen anyway. It would radically change how all existing switches behaves re `null`. 3/5
But if `case null` and `default` need the same reaction, you can combine the two branches. I guess that's gonna become the new norm in many code bases. Not mine, though, I want NPEs for my `null`s. (And you can combine `null` with other labels as is allowed since #Java14.) 4/5
Note that while I only showed `case null` with normal switch expressions that use the arrow, they work across all combinations { normal, pattern } × { expression, statement } × { colon, arrow }. 5/5