【问题标题】:Groovy equivalent to OCL forAllGroovy 相当于 OCL forAll
【发布时间】:2012-08-14 15:31:34
【问题描述】:

什么是与 OCL 中的 forAll 方法等效的 Groovy?


假设我有一个项目列表。

def items = new LinkedList<Item>();

表达当且仅当所有项目都符合特定条件时才成立的谓词的 Groovy 方法是什么?


下面的代码sn-p是不行的,因为内部的return只是跳出了each闭包的当前迭代,没有跳出forAll方法。

boolean forAll(def items)
{
    items.each { item -> if (!item.matchesCriteria()) return false; };
    return true;
}

下面的代码 sn-p 应该可以解决问题,但感觉很麻烦,而且不像 Groovy。

boolean forAll(def items)
{
    boolean acceptable = true;
    items.each { item -> if (!item.matchesCriteria()) acceptable = false; };
    return acceptable;
}

我正在寻找一种懒惰地评估谓词的方法,以便在找到第一个不匹配项时完成评估。

【问题讨论】:

    标签: groovy ocl


    【解决方案1】:

    您可以使用every

    items.every { it.matchesCriteria() }
    

    【讨论】:

      【解决方案2】:

      在 groovy 中这很容易:

      def yourCollection = [0,1,"", "sunshine", true,false]
      
      assert yourCollection.any() // If any element is true
      

      或者如果你想确定,一切都是真的

      assert !yourCollection.every() 
      

      你甚至可以用闭包来做到这一点

      assert yourCollection.any { it == "sunshine" } // matches one element, and returns true
      

      assert !yourCollection.every { it == "sunshine" } // does not match all elements
      

      【讨论】:

        猜你喜欢
        • 2013-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-19
        • 2020-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多