Those Brackets Really Matter in a Groovy Switch!

I’ve been working on a data detector plugin for Grails as a side project, and thought it important to mention the importance of including brackets {} for logic statements in groovy switches.

Below I have a simple detector for a simple DataType enum that has STRING and DECIMAL (which in my real code is BigDecimal)  types.

public enum DataType { STRING, DECIMAL }

Is you leave the {} from around NumberUtils.isNumber — everything comes back STRING!  So make sure you include them even for a one-step logic decision:

public static DataType detectTypeFromString(String data) {
        switch (data) {
            case { NumberUtils.isNumber(data) }:
                return DataType.DECIMAL
            default:
                return DataType.STRING
        }
    }

Of course it makes a lot more sense if you have a compound statement. Here, a number is defined from a string as 0 or any number that doesn’t start with 0 because it would be an identifier:

public static DataType detectTypeFromString(String data) {
        switch (data) {
            case { data?.equals('0') || (!data?.startsWith('0') 
&& NumberUtils.isNumber(data)) }:
                return DataType.DECIMAL
            default:
                return DataType.STRING
        }
    }

So I make sure I am careful about the syntax, especially groovy where tiny little syntax characters make a big difference!

, ,

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>