groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Dinko Srko─Ź <dinko.sr...@gmail.com>
Subject Re: Curious that Groovy case can match values that are not equal to the candidate
Date Sun, 09 Aug 2015 23:08:52 GMT
On 7 August 2015 at 23:05, KARR, DAVID <dk068x@att.com> wrote:
> Reading REGINA, I find this detail of Groovy semantics very curious:
> ----------------------
> def myList = ['a', 'b', 'c']
> switch ('c') {
> case myList: assert true;break;
> default: assert false;break;
> }
> --------------
>
> In all the languages I'm aware of with some sort of "switch/case" construct, you can
always assume that if the "case" matches, then the "case" value "is equal to" the switch candidate.
 This is the first time I've seen this not be the case.

Let's not stop at Groovy ;-) . Here's more or less the same example using Ruby:

  $ irb
  irb(main):001:0> xs = 'a'..'c'
  => "a".."c"
  irb(main):002:0> case 'c'
  irb(main):003:1>   when xs then true
  irb(main):004:1>   else false
  irb(main):005:1> end
  => true

Ruby's version of Groovy's `isCase()` method is `===` operator.

Parenthetically, I had to use a Range because Array apparently doesn't
implement `===` (hence `'a'..'c'` instead of `['a', 'b', 'c']`)

Cheers,
Dinko

>
> I certainly understand what Groovy is doing here, and I appreciate the power of it, it's
just a bit surprising.

Mime
View raw message