groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Dmitry Semionin <dmitry.semio...@gmail.com>
Subject Interpolated strings and embedded closures
Date Sat, 18 Jul 2015 21:41:10 GMT
Hello everybody.

I'm totally new to Groovy, and thought it would be right to start learning
it by studying the online documentation on the official website. One of the
topics i didn't quite understand was the string interpolation in
conjunction with closures.
The documentation offers the following example:

def sOneParamClosure = "1 + 2 == ${ w -> w << 3}" assert
sOneParamClosure == '1 + 2 == 3'

with the following comment: "Here, the closure takes a single
java.io.StringWriter argument, to which you can append content with the <<
leftShift operator."

I have several questions about the code above:

1. Why is w stated to be of type java.io.StringWriter? Why can't it be of
any other type compatible with the << operator, any integer type for
example?
2. The embedded closure from the code above has an argument, but how would
one pass a parameter to such closure? Would doing it even make sense, or
the embedded closures are some special kind that either takes no params or
a single implicit param of type java.io.StringWriter?
3. If there's no way to make such closures have arguments of arbitrary
types and pass parameters to them, then what's the point in such closures
at all? The doc says that closures have a benefit of a lazy variable
evaluation, and that is important, but one doesn't need a parameterized
closure to achieve it. So what am i missing?

I'll be very grateful for any help you guys could provide!

- Dmitry

Mime
View raw message