Groovy's HERE DOCUMENT and Closure

阅读更多
Something fun with Groovy's 'HERE DOCUMENT', i.e., """..."""

In groovyConsole, execute (Ctrl + R) following code:
"""
${ println "Hi" }
"""

result: Hi
Cool, isn't it?

How about this?
"""
${
class Foo{}
}
"""
No way...Why?

The curly braces denote a closure,  So, we can put anything valid in a closure into the ${} within a HERE DOC:

a = [1,2,3,4,5,6]

"""
${
a.each {print it}
}
"""

result: 123456
Wow, closure within closure. So below is nothing strange:

"""
${
println """ ${println "Can you see me?"} """
}
"""

result: yes, I can :)

你可能感兴趣的:(Groovy)