Reputation: 2430
Why do some core taglibs in Grails return a closure? For example createLink
(see source)? What are the benefits or use cases?
Upvotes: 0
Views: 57
Reputation: 24776
So, what you are actually seeing is that createLink
is defined as a Closure
, not that it's returning a Closure
when it's executed. The closure itself is executed and delegates the implementation which is responsible for the actual work of creating the StreamCharBuffer
.
Let's look at the source and see what's really going on:
Closure createLink = { attrs ->
return doCreateLink(attrs instanceof Map ? (Map) attrs : Collections.emptyMap())
}
As you can see above we have a variable called createLink
of type Closure
which delegates it's work to doCreateLink
. Which happens to be a protected method within the containing class.
protected String doCreateLink(Map attrs) {
... // actual implementation cut out of this example
return useJsessionId ? res.encodeURL(generatedLink) : generatedLink
}
As you can see this is where the actual work is done to generate the StreamCharBuffer
(Well, String
, which casts nicely).
Now, why would you do this? One possible use case is, the method doCreateLink
is much more strict than the closure createLink
in the formal definition. By using a Closure
instead of the method, the call to createLink
can change slightly over time as enhancements or additions are made to it with (hopefully) little or no impact to previous uses of it.
Hopefully that helps explain a bit about what you are seeing and possibly why.
Upvotes: 3