Using Static String in Groovy Switch-Case Statement

10,846

I know this doesn't answer your question of why your code is not working for you, but if you want a slightly groovier/better way to implement your code you could throw your values into a map so then you wouldn't have to use a switch statement:

class ValueTests {
    public static final String HIGH_STRING = "high"
    public static final String LOW_STRING  = "low"

    @Test
    void stuff() {
        assert "string was high" == getValue("high")
        assert "string was low" == getValue("low")
        assert "no match" == getValue("higher")
    }

    def getValue(String key) {
        def valuesMap = [
            (HIGH_STRING): "string was high", 
            (LOW_STRING):"string was low"
        ]
        valuesMap.get(key) ?: "no match"
    }

}

A little cleaner than a switch IMO.

Share:
10,846
Marc
Author by

Marc

Updated on June 05, 2022

Comments

  • Marc
    Marc almost 2 years

    I'm a Java programmer who's dabbling in Groovy. You'll note in my code that I mix in some Java-specific syntax, which is supposedly A-Okay with Groovy.

    Can anyone explain to me why Groovy won't accept a static variable as a CASE parameter? Or if it will, can you see what I'm doing wrong here?

    public static final String HIGH_STRING = "high";
    public static final String LOW_STRING  = "low";
    
    ... //other code, method signature, etc.
    
    def val = "high";
    switch (val) {
    
       case HIGH_STRING:
         println("string was high"); //this won't match
         break;
    
       case LOW_STRING:
         println("string was low");  //this won't match
         break;
    
       //case "high":
       //  println("string was high"); //this will match because "high" is a literal
       //  break;
    
       default:
         println("no match");
    }
    
    ... //other code, method closeout, etc.
    
  • Marc
    Marc almost 12 years
    this isn't exactly what I was looking for, but you'll see from my comment above that it was my own lackadaisical fault that this wasn't working. Interesting approach that you provided here though, and it's the closest thing anyone's posted to a correct answer, so I'll accept it. I like to learn new ways to approach this stuff, so thanks for taking the time!