int 类型 > Groovy 中的运算符错误

int type > operator error in Groovy

使用Groovy,>运算符警告类型匹配错误。

这是一个问题:

def greaterThan50(nums){
   def result = []
   nums.each{ num ->
      if(num > 50)
         result << num
   result
}
def test = greaterThan50([2, 3, 50, 62, 11, 2999])
assert test.contains(62)

“if(num > 50)”行创建警告。

[静态类型检查] - 找不到匹配方法 java.lang.Object#compareTo(java.lang.Integer)。请检查声明的类型是否正确,方法是否存在

50是int类型(据我所知也是一个对象)但是网站的例子是这样的。 (网站在这里:http://docs.smartthings.com/en/latest/getting-started/groovy-basics.html#groovy-basics

def greaterThan50(nums){
   def result = []
   for (num in nums){
       if(num > 50){
            result << num
       }
   }
   result
}
def test = greaterThan50([2, 5, 62, 50, 25, 88])

如何更改用于比较两个 int 类型的代码?

如果您需要抑制警告,有效地静态检查该代码,您可以显式声明传入参数的数据类型。

def greaterThan50(List<Integer> nums){

这将允许静态类型检查 link 迭代元素类型为整数。

要使类型检查正常工作,您需要明确指定参数和 return 类型。您还错过了在 each.

之后结束闭包的右大括号
List<Integer> greaterThan50(List<Integer> nums) {
    def result = []
    nums.each { num ->
        if (num > 50)
            result << num
    }
    result
}

def test = greaterThan50([2, 3, 50, 62, 11, 2999])
assert test.contains(62)

归档相同功能的更常规方法是

nums.findAll { it > 50 }

这会创建一个新列表并为您添加所有满足条件的数字。