groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jochen Theodorou <>
Subject Re: Interpolated strings and embedded closures
Date Sun, 19 Jul 2015 06:14:37 GMT
Am 18.07.2015 23:41, schrieb Dmitry Semionin:
> 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
> || 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 ||? Why can't it
> be of any other type compatible with the |<<| operator, any integer type
> for example?

parameter = variable (with type) declared in a method/closure
argument  = value (with type) used to call a method/closure

So it means the closure is called with a value of type StringWriter. The 
parameter can of course have any type that is a parent to StringWriter. 
No type being used means for example Object. But if you supply an 
incompatible type, you will get an exception on call. For example if you 
give the parameter w the type int, then you do have leftShift on there, 
but the method call to the closure itself is still done with a 
StringWriter and will fail.

> 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 ||?
> 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?

You have argument and parameter wrong. Does my definition of parameter 
and argument above explain this as well to you?

bye blackdrag

Jochen "blackdrag" Theodorou

View raw message