2017-06-13 37 views
0

我想用switch語句來檢查一個對象是否是特定類型的實例,如果是的話我想設置一個字符串變量然後在最後返回它在方法。在switch語句中設置一個變量Groovy

每當我運行我的測試'detailMessage'總是會返回爲空,我是不正確地做開關情況?

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

您不需要使用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 
     }