Groovy比较链 [英] Groovy comparison chaining

查看:167
本文介绍了Groovy比较链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,以下语句返回正确的结果:

In python the following statement returns correct results:

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

这样的结构groovy?以下失败:

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

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

因为第一次比较被评估为 true true 不等于 1

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

推荐答案

或者如果不是你遇到的AST路由:

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

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

你可以用

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

assert allEqual(1, 1, 1)

这篇关于Groovy比较链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆