Exhaustiveness in switch

Dan Smith daniel.smith at oracle.com
Thu May 10 22:28:02 UTC 2018

> On May 10, 2018, at 2:46 PM, Guy Steele <guy.steele at oracle.com> wrote:
>> On May 10, 2018, at 4:54 PM, Brian Goetz <brian.goetz at oracle.com <mailto:brian.goetz at oracle.com>> wrote:
>>> * It would feel strange to even bother applying this exhaustiveness goo to byte switches. If we ever had ranges.... of course then, any type of switch could join the party. (I don't know whether ranges are a thing we're considering or not and I'm not pushing that we do.)
>> Yeah, its on the edge.  Its a no-brainer for `boolean`, its nuts for `int` (without ranges), but its vaguely defensible for `byte`.  Though I can't really get too excited about it.
> The choice is not just among four sizes of integer.  One could imagine recognizing certain idioms such as
> 	switch (myInt & 7) {
> 	  case 2, 3, 5, 7 -> “prime”;
> 	  case 0, 1, 4 -> “square”;
> 	  case 6 -> “perfect”;
> 	}
> and understanding that they are exhaustive.  Dunno if the compiler guys want to go there.

We can teach the compiler a few properties of primitive numbers, but we can't effectively teach it about a random WidgetStateMachine. (Like, maybe if one field is null, then the WidgetState will be one of 3 possible enum values, out of 33 total. This is totally obvious to people who know about WidgetStateMachines, why does the compiler make me write extra code?!?)

But an idea I've raised is that while the compiler's ability to prove exhaustiveness will always be limited, a user might appreciate _asserting_ exhaustiveness in some extremely lightweight way. That would opt out of any compile-time checking ("looks like you missed a case"), and instead, like a cast, would give you runtime checks for unexpected inputs ("you told me I wouldn't see this value, but I did").

Brian's response to this, conveyed in the OP, is that he sees forcing an explicit "default -> unexpected input" case as a feature, not a bug. Which, yeah, I can see a reader sometimes wanting an explanation in an error message. But sometimes I think you just want to implicitly assert something you expect to be true ("this Object is a String", "this value can be dereferenced", "this number is a valid array index").

The bottom line is that it's not clear whether that extra modifier on switch (or whatever) which would opt in to runtime checking is worth the extra complexity. But maybe there's something there, in conjunction with a modifier (or whatever) which would opt in to compile-time checking.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20180510/d3356849/attachment.html>

More information about the amber-spec-experts mailing list