我正在尝试使用 switch 语句来检查对象是否是特定类型的实例,如果是,我想设置一个字符串变量,然后在方法末尾返回它。
每当我运行测试时,“detailMessage”总是返回为 null,我是否错误地执行了 switch case?
private String returnDetailMessage(Discount discountType, Object quantity, Object claims) {
String detailMessage
switch (objectType) {
case objectType instanceof Percentage:
if (quantity > claims) {
detailMessage = "There are not enough discounted strings for you to do this"
break
} else {
detailMessage = "this is a discount string."
break
}
case objectType instanceof FixedAmount:
if (quantity > claims) {
detailMessage = "There are not enough discounted Strings to cover the amount of quantity you have"
break
} else {
detailMessage = "there is a fixed amount here where quantity is less than claims"
break
}
}
return detailMessage
}
最佳答案
不需要使用instanceof,只需指定类即可。
此外,当从折扣类型中提取字段时,我们仅使用该字段而不是特定的百分比/固定金额类型?
private String returnDetailMessage(Discount discountType, Object quantity, Object claims) {
String detailMessage
switch (discountType) {
case Percentage:
if (quantity > claims) {
detailMessage = "There are not enough discounted strings for you to do this"
break
} else {
detailMessage = "this is a discount string."
break
}
case FixedAmount:
if (quantity > claims) {
detailMessage = "There are not enough discounted Strings to cover the amount of quantity you have"
break
} else {
detailMessage = "there is a fixed amount here where quantity is less than claims"
break
}
}
return detailMessage
}
关于java - 在 switch 语句中设置变量 Groovy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44514600/