Andrey Hihlovskiy

Professional blog on groovy, gradle, Java, Javascript and other stuff.

groovy switch: nasty bug

I found nasty error in Groovy compiler. Consider the following code:

byte b = 1
switch(b) {
  case 0..9:
    println 'it is between 0 and 9'
    break
  default:
    println 'it is something else'
}

It executes ‘default’ part, not the part with 0..9, which is not what a programmer would typically expect.
The reason behind it should be related to type conversion between “byte” and “int” types. With the following workaround:

switch((int)b)

the program executes “proper” case.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: