Using Static String in Groovy Shutdown Statement

I am a Java programmer who works in Groovy. In my code, you'll notice that I'm mixing some Java-specific syntax, presumably A-Okay with Groovy.

Can someone explain to me why Groovy is not accepting a static variable as a parameter CASE? Or, if so, 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.
+3
source share
1 answer

I know this does not answer your question about why your code does not work for you, but if you want a slightly more attractive / better way to implement your code, you can throw your values ​​on the map so that you do not have to use the operator switch:

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 switchIMO.

+4
source

All Articles