2017-06-13 9 views
0

switch文を使用して、オブジェクトが特定の型のインスタンスであるかどうかをチェックしようとしていますが、文字列変数を設定して、方法。switch文中に変数を設定するGroovy

私のテストを実行するたびに、 '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

instanceofを使用する必要はありません。クラスを指定するだけです。

また、discountTypeからフィールドを引き出すときには、特定のpercentage/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 
     }