Groovy comparison chaining

﹥>﹥吖頭↗ 提交于 2019-12-12 03:37:24

问题


In python the following statement returns correct results:

>>> 1 == 1 == 1
True
>>> 1 == 1 == 0
False

Is such construct (or similar) possible in groovy? The following fails:

groovy:000> 1 == 1 == 1
===> false

since the first comparison is evaluated to true and true is not equal to 1. Any workaround on this?


回答1:


A workaround would be using AST transformations of course: http://docs.groovy-lang.org/docs/next/html/documentation/core-metaprogramming.html#developing-ast-xforms




回答2:


Or if not the AST route you're stuck with:

(1 == 1) && (1 == 1)

Which you could do programatically with something like:

public <T> Boolean allEqual(T... elements) {
    elements.toList().collate(2, 1, false).every { a, b -> a == b }
}

assert allEqual(1, 1, 1)


来源:https://stackoverflow.com/questions/30796670/groovy-comparison-chaining

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!