Kar*_*yan 24 each groovy for-loop continue spock
我是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);
}
Run Code Online (Sandbox Code Playgroud)
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)
}
Run Code Online (Sandbox Code Playgroud)
Vam*_*ire 43
要么使用return,因为闭包基本上是一个用每个元素作为参数调用的方法
def myObj = ["Hello", "World!", "How", "Are", "You"]
myList.each{ myObj->
if(myObj==null){
return
}
println("My Object is " + myObj)
}
Run Code Online (Sandbox Code Playgroud)
或者将模式切换为
def myObj = ["Hello", "World!", "How", "Are", "You"]
myList.each{ myObj->
if(myObj!=null){
println("My Object is " + myObj)
}
}
Run Code Online (Sandbox Code Playgroud)
或者使用findAllbefore来过滤掉null对象
def myList = ["Hello", "World!", "How", "Are", null, "You"]
myList.findAll { it != null }.each{ myObj->
println("My Object is " + myObj)
}
Run Code Online (Sandbox Code Playgroud)
inj*_*eer 15
您可以使用标准for循环continue:
for( String myObj in myList ){
if( something ) continue
doTheRest()
}
Run Code Online (Sandbox Code Playgroud)
或使用return中each的关闭:
myList.each{ myObj->
if( something ) return
doTheRest()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22812 次 |
| 最近记录: |