2014年2月18日 星期二

[ In Action ] Groovy control structures - Looping

Preface: 
The structures you’ve seen so far have evaluated a Boolean test once and changed the path of execution once based on the result of the condition. Looping, on the other hand, repeats the execution of a block of code multiple times. The loops available in Groovy are while and for , both of which we cover here. 

Looping with while: 
The while construct is like its Java counterpart. The only difference is the one you’ve seen already—the power of Groovy Boolean test expressions. To summarize very briefly, the Boolean test is evaluated, and if it’s true, the body of the loop is then executed. The test is then re-evaluated, and so forth. Only when the test becomes false does control proceed past the while loop. Listing 6.8 shows an example that removes all entries from a list. 
- Listing 6.8 Example while loops 
  1. def list = [1,2,3]  
  2. while (list) {  
  3.     list.remove(0)  
  4. }  
  5. assert list == []  
  6. while (list.size() < 3) list << list.size()+1  
  7. assert list == [1,2,3]  
Again, there should be no surprises in this code, with the exception of using just list as the Boolean test in the first loop. Note that there are no do{}while(condition) or repeat{}until(condition) loops in Groovy. 

Looping with for: 
Considering it is probably the most commonly used type of loop, the for loop in Java is relatively hard to use, when you examine it closely. Through familiarity, people who have used a language with a similar structure (and there are many such languages) grow to find it easy to use, but that is solely due to frequent use, not due to good design. Although the nature of the traditional for loop is powerful, it is rarely used in a way that can’t be more simply expressed in terms of iterating through a collection-like data structure. Groovy embraces this simplicity, leading to probably the biggest difference in control structures between Java and Groovy. 

Groovy for loops follow this structure: 
for (variable in iterable) { body }

where variable may optionally have a declared type. The Groovy for loop iterates over the iterable. Frequently used iterables are ranges, collections, maps, arrays, iterators, and enumerations. In fact, any object can be an iterable. Groovy applies the same logic as for object iteration, described in chapter 8. 

Curly braces around the body are optional if it consists of only one statement. Listing 6.9 shows some of the possible combinations. 
- Listing 6.9 Multiple for loop examples 
  1. // 1) Typed, over string range, no braces  
  2. def store = ''  
  3. for (String i in 'a'..'c') store += i  
  4. assert store == 'abc'  
  5.   
  6. // 2) Untyped, over list as collection, braces  
  7. store = ''  
  8. for (i in [123]) {  
  9.     store += i  
  10. }  
  11. assert store == '123'  
  12.   
  13. // 3) Untyped, over half-exclusive IntRange, braces  
  14. def myString = 'Equivalent to Java'  
  15. store = ''  
  16. for (i in 0 ..< myString.size()) {  
  17.     store += myString[i]  
  18. }  
  19. assert store == myString  
  20.               
  21. // 4) Untyped, over string as collection, braces  
  22. store = ''  
  23. for (i in myString) {  
  24.     store += i  
  25. }  
  26. assert store == myString  
Using the for loop with object iteration as described in section 9.1.3 provides some very powerful combinations. 

You can use it to print a file line-by-line via 
  1. def file = new File('myFileName.txt')  
  2. for (line in file) println line  
or to print all one-digit matches of a regular expression: 
  1. def matcher = '12xy3'=~/\d/  
  2. for (match in matcher) println match  
If the container object is null, no iteration will occur: 
  1. for (x in null) println 'This will not be printed!'  
If Groovy cannot make the container object iterable by any means, the fallback solution is to do an iteration that contains only the container object itself
  1. for (x in new Object()) println "Printed once for object $x"  
Object iteration makes the Groovy for loop a sophisticated control structure. It is a valid counterpart to using methods that iterate over an object with closures, such as using Collection ’s each method. The main difference is that the body of a for loop is not a closure! That means this body is a block: 
  1. for (x in 0..9) { println x }    
whereas this body is a closure: 
  1. (0..9).each { println it }     
Even though they look similar, they are very different in construction. 

Supplement: 
Groovy Document > Control Structures > Looping

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...