我是groovy的新手(曾在java上工作),尝试使用Spock框架编写一些测试用例。 我需要将以下Java代码段转换为groovy代码段,使用"每个循环"
List<String> myList = Arrays.asList("Hello", "World!", "How", "Are", "You");
for( String myObj : myList){
if(myObj==null) {
continue; // need to convert this part in groovy using each loop
}
System.out.println("My Object is "+ myObj);
}
Groovy Snippet:
def myObj = ["Hello", "World!", "How", "Are", "You"]
myList.each{ myObj->
if(myObj==null){
//here I need to continue
}
println("My Object is " + myObj)
}
答案 0 :(得分:36)
使用return
,因为闭包基本上是一个方法,每个元素作为参数调用,如
def myObj = ["Hello", "World!", "How", "Are", "You"]
myList.each{ myObj->
if(myObj==null){
return
}
println("My Object is " + myObj)
}
或将模式切换为
def myObj = ["Hello", "World!", "How", "Are", "You"]
myList.each{ myObj->
if(myObj!=null){
println("My Object is " + myObj)
}
}
或者之前使用findAll
过滤掉null
个对象
def myList = ["Hello", "World!", "How", "Are", null, "You"]
myList.findAll { it != null }.each{ myObj->
println("My Object is " + myObj)
}
答案 1 :(得分:14)
您可以使用标准continue
循环for( String myObj in myList ){
if( something ) continue
doTheRest()
}
:
return
或在each
关闭时使用myList.each{ myObj->
if( something ) return
doTheRest()
}
:
for (username in users) { ..
答案 2 :(得分:1)
如果对象不是if
,您也只能输入null
语句。
def myObj = ["Hello", "World!", "How", "Are", "You"]
myList.each{
myObj->
if(myObj!=null){
println("My Object is " + myObj)
}
}