使用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)
该行&#34; if(num> 50)&#34;创建警告。
[静态类型检查] - 找不到匹配方法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类型的代码?
答案 0 :(得分:0)
如果您需要禁止警告,有效地使代码静态检查,您可以显式声明传入参数的数据类型。
def greaterThan50(List<Integer> nums){
这将允许静态类型检查将迭代元素类型链接到Integer。
答案 1 :(得分:0)
要使类型检查正常工作,您需要显式指定参数和返回类型。你还错过了一个结束括号来结束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)
存档相同功能的groovyier方法是
nums.findAll { it > 50 }
创建一个新列表并添加满足条件的所有数字。