user1768830
user1768830

Reputation:

What's wrong with this Groovy expression?

Running the following Groovy expression through the GroovyShell (interpreter):

if(fizz.subtype == null) {
    if(fizz.color == 'RED') fizz.subtype = "DOG";
    else if(fizz.color == 'BLUE') fizz.subtype = "CAT";
    else if(fizz.color == 'GREEN') fizz.subtype = "SHEEP";
    else if(fizz.color == 'ORANGE') fizz.subtype = "LION";
    else if(fizz.color == 'YELLOW') fizz.subtype = "SNAIL";
    else if(fizz.color == 'GRAY') fizz.subtype = "SHARK";
    else if(fizz.color == 'PURPLE') fizz.subtype = "BAT";
    else if(fizz.color == 'BLACK') fizz.subtype = "FOX";
}; fizz;

Gives me the following stack trace:

groovy.lang.MissingPropertyException: No such property: subtype for class: com.me.myapp.Fizz
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:50)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.getProperty(ScriptBytecodeAdapter.java:479)
    at Script1.run(Script1.groovy:1)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:543)
    at groovy.lang.GroovyShell.evaluate(GroovyShell.java:518)
    at com.tms.evaluator.GroovyEvaluator._evaluate(GroovyEvaluator.java:51)
    ...rest of stacktrace omitted for brevity

Any ideas? Thanks in advance!

Upvotes: 1

Views: 194

Answers (1)

Will
Will

Reputation: 14559

You are missing a semicolon after the closing bracket of the if expression:

fizz = [:]
if(fizz.subtype == null) {
    if(fizz.color == 'RED') fizz.subtype = "DOG";
    else if(fizz.color == 'BLUE') fizz.subtype = "CAT";
    else if(fizz.color == 'GREEN') fizz.subtype = "SHEEP";
    else if(fizz.color == 'ORANGE') fizz.subtype = "LION";
    else if(fizz.color == 'YELLOW') fizz.subtype = "SNAIL";
    else if(fizz.color == 'GRAY') fizz.subtype = "SHARK";
    else if(fizz.color == 'PURPLE') fizz.subtype = "BAT";
    else if(fizz.color == 'BLACK') fizz.subtype = "FOX";
}; fizz;

Also, may i suggest using a map for this kind of data matching?

fizz.color = 'ORANGE'

fizz.subtype = [
    'RED'    : 'DOG',
    'BLUE'   : "CAT",
    'GREEN'  : "SHEEP",
    'ORANGE' : "LION",
    'YELLOW' : "SNAIL",
    'GRAY'   : "SHARK",
    'PURPLE' : "BAT",
    'BLACK'  : "FOX"
][fizz.color]

assert fizz.subtype == 'LION'

A case-match could also work, but it would be best suited if you had a more complex task:

fizz.color = 'BLUE'

fizz.subtype = fizz.color.case {
    when 'RED'    then 'DOG'
    when 'BLUE'   then "CAT"
    when 'GREEN'  then "SHEEP"
    when 'ORANGE' then "LION"
    when 'YELLOW' then "SNAIL"
    when 'GRAY'   then "SHARK"
    when 'PURPLE' then "BAT"
    when 'BLACK'  then "FOX"
}

assert fizz.subtype == 'CAT'

Upvotes: 1

Related Questions