4 ms·
While we're talking about terrible decisions, can you guess what the following code will print? String s = null; switch (s) { default: Syst
by crehn 6y ago
While we're talking about terrible decisions, can you guess what the following code will print?
String s = null;
switch (s) {
default:
System.out.println("Hey");
}
Hint: it will throw NullPointerException.
- bcrosby95 6y agoDon't worry, there's a whole new set of terrible decisions with switch expressions.
- rwmj 6y agoI'm confused why you'd want it to do anything else. Perhaps you could give a more realistic example to motivate the argument for why the behaviour is wrong or inconvenient?
- shakna 6y agoI assume this is because null is false-y in many other languages, and can be used in switch/if statements and so on. Rather than having to be treated like an error.
- rovolo 6y agoIt's inconvenient because null could be considered a case switch(s) { case null: return false; case "y": return true; default: return false; } The broader issue is that Java handles null inconveniently. 1) Every object can be null, switch requires the argument to be non-null, and the type system doesn't warn you when NPE are possible. A type system which handles nullability could fail to compile if 's' is nullable. Kotlin does this, and it let's you opt-in to the NPE with some convenient syntax: switch(s!!) 2) It's inconvenient to handle null as a value. To properly handle the null case without throwing, you need to do one the following: if(s == null) { ... } else switch(s) { ... } switch(s == null ? "some-default" : s) The first way can be made more convenient if you change switch to work on nullable values. The second way is inconvenient, so people generally skip it. If you want switch to only work on non-null values, there're more convenient syntaxes to handle null, such as the 'elvis operator': switch(s ?: "some-default")
- whitenoice 6y agoYou could also use Optional, like Optional.ofNullable(s).map(i -> {switch (i) {...}}).orElse()