我做错了什么:
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
有没有办法在不将值转换为数字类型的情况下执行此操作?
答案 0 :(得分:0)
对你的问题的简短回答是否定的。
但是,我觉得这是出于分类的目的。如果是这样的话。这是我用于此目的的排序函数。
行动中的示例:Groovy Web Console
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)