gpt4 book ai didi

groovy - 这个Groovy表达式有什么问题?

转载 作者:行者123 更新时间:2023-12-03 08:08:58 25 4
gpt4 key购买 nike

通过GroovyShell(解释器)运行以下Groovy表达式:

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;

给我以下堆栈跟踪:
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

有任何想法吗?提前致谢!

最佳答案

您在if表达式的右括号后缺少分号:

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;

另外,我可以建议使用 map 进行此类数据匹配吗?
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'

case-match也可以工作,但是如果您有更复杂的任务,则最适合:
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'

关于groovy - 这个Groovy表达式有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19344852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com