0

我做错了什么:

assert  'foo'  == 'foo'  //PASS
assert  '500'  == '500'  //PASS
assert  '500'  <  '1000' //FAIL <-- Supposed to pass
assert  '500'  <= '1000' //FAIL <-- Supposed to pass
assert  '1000' >  '500'  //FAIL <-- Supposed to pass
assert  '1000' >= '500'  //FAIL <-- Supposed to pass

它适用于可定制的“条件”对象:

class Condition {
    static def compareClosure = [
            '==' : { a, b -> a == b},
            '!=' : { a, b -> a != b},
            '<'  : { a, b -> a <  b},
            '<=' : { a, b -> a <= b},
            '>'  : { a, b -> a >  b},
            '>=' : { a, b -> a >= b}
    ]

    String comparator
    def value

    Condition(String comparator, String value) {
        this.value = value
        this.comparator = comparator
    }

    boolean isSatisfiedBy(def value) {
        compareClosure[comparator](value, this.value)
    }
}

所以

assert new Condition('<=', '1000').isSatisfiedBy('500') //FAIL

有没有办法在不将值转换为数字类型的情况下做到这一点?

4

1 回答 1

0

您的问题的简短回答是否定的。

但是,我觉得这是为了排序。如果是这样的话。这是我为此目的使用的排序功能。

实际示例:Groovy Web 控制台

    Closure customSort = { String a, String b ->
      def c = a.isBigDecimal() ? new BigDecimal(a) : a
      def d = b.isBigDecimal() ? new BigDecimal(b) : b


      if (c.class == d.class) {
        return c <=> d
      } else if (c instanceof BigDecimal) {
        return -1
      } else {
        return 1
      }

    }

['foo','500','1000', '999', 'abc'].sort(customSort)
于 2013-03-21T22:36:32.910 回答