Guards -- not just for switch!
Guy Steele
guy.steele at oracle.com
Wed Nov 29 21:49:23 UTC 2017
Um, let’s be careful here. See below.
> On Nov 29, 2017, at 4:54 PM, Brian Goetz <brian.goetz at oracle.com> wrote:
>
> As we've swirled around the design space on pattern matching, it seems the sensible place to land is to not provide explicit syntax for AND and OR patterns, but to support guards on case labels:
>
> case Foo(String s)
> where (s.length() > 0): ...
>
> In the course of a separate discussion, we realized that guards can profitably go in some other places, too. Like methods/constructors:
>
> public Range(int lo, int hi)
> where (lo <= hi) {
> this.lo = lo;
> this.hi = hi;
> }
>
The two situations are not analogous, because if a case clause fails you just try the next one, but if a constructor fails you don’t try another constructor.
If we use the term “where” on a constructor, then Joe Programmer (that's me) will probably be very surprised if
switch (x) {
case Foo(String s)
where (s.length() > 0): ...
case Foo(String s)
where (s.length() == 0): ...
}
works, but
public Interval(int lo, int hi)
where (lo <= hi) {
this.lo = lo;
this.hi = hi;
this.exterior = false;
}
public Interval(int lo, int hi)
where (lo > hi) {
this.lo = lo;
this.hi = hi;
this.exterior = true;
}
does not work.
It might make sense to use a word such as “requires” or “assert” rather than “where” in the constructor case.
—Guy
More information about the amber-spec-experts
mailing list