groovyprintln

Range and list in Groovy not fully printed out


Can anyone explain why lines 1a and 2a do not print out the entire range but lines 1b, 1c, 2b and 2c do?

Script

println GroovySystem.version
def range = 1..5
printf "1a: range %s %n", range
printf "1b: range %s %n", range.toString()
printf "1c: range %s %n", range, ""
printf "2a: range %s %n", range.asList()
printf "2b: range %s %n", range.asList().toString()
printf "2c: range %s %n", range.asList(), ""

Output

3.0.9
1a: range 1 
1b: range 1..5 
1c: range 1..5 
2a: range 1 
2b: range 1..5 
2c: range 1..5 

I am new to groovy but I would expect 1a and 1c to be the same (likewise for 2a and 2c).


Solution

  • def range = 1..5
    
    printf "1a: range %s %n", range
    printf "1b: range %s %n", 1,2,3,4,5    //same as 1a
    printf "1c: range %s %n", *range, ""   //same as 1,2,3,4,5,""
    
    printf "2a: range %s %n", range, ""
    printf "2b: range %s %n", [range, ""]  //same as 2a
    printf "2c: range %s %n", [range]
    

    result

    1a: range 1 
    1b: range 1 
    1c: range 1 
    2a: range 1..5 
    2b: range 1..5 
    2c: range 1..5 
    

    all parameters to printf passed as a list.

    so, if you passing just one parameter that is a list then every element of list considered as a separate parameter.

    it means that 1a and 1b are equivalent

    that's why all 1* examples giving just a first element of a list (range)

    2c shows a workaround for this