在switch语句Groovy中设置一个变量

时间:2017-06-13 07:11:26

标签: java groovy switch-statement

我正在尝试使用switch语句来检查对象是否是特定类型的实例,如果是,我想设置一个字符串变量,然后在方法的末尾返回它。

每当我运行我的测试时,'detailMessage'总是以null返回,我是否错误地处理了切换案例?

 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
        }

1 个答案:

答案 0 :(得分:1)

您不需要使用instanceof,只需指定类。

同样,当从discountType中提取字段时,我们只使用它而不是特定的百分比/ fixedAmount类型?

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
        }