When I sat down to write about injections, I thought it’d be a quick little blog post.  However, it took me a lot longer than I expected to get my head around even the basic concept of what the injection was actually doing.
I get the general idea now, but I don’t see myself putting them into action in my code very often.

This is the best example I could find of an injection in action.

Here’s a quick exploration of some injection code, as I understood it:

(1..5).inject(1) { runningTotal, itemInRange ->

 log.warn("$runningTotal * $itemInRange = ${runningTotal * itemInRange}")

log.warn("The running total is $runningTotal and the current item from the range is $itemInRange")

 runningTotal * itemInRange 

}

 

The results looked like this:

2023-02-22T03:55:55,063 WARN [runner.ScriptBindingsManager]: 1 * 1 = 1
2023-02-22T03:55:55,063 WARN [runner.ScriptBindingsManager]: The running total is 1 and the current item from the range is 1
2023-02-22T03:55:55,063 WARN [runner.ScriptBindingsManager]: 1 * 2 = 2
2023-02-22T03:55:55,063 WARN [runner.ScriptBindingsManager]: The running total is 1 and the current item from the range is 2
2023-02-22T03:55:55,063 WARN [runner.ScriptBindingsManager]: 2 * 3 = 6
2023-02-22T03:55:55,063 WARN [runner.ScriptBindingsManager]: The running total is 2 and the current item from the range is 3
2023-02-22T03:55:55,063 WARN [runner.ScriptBindingsManager]: 6 * 4 = 24
2023-02-22T03:55:55,063 WARN [runner.ScriptBindingsManager]: The running total is 6 and the current item from the range is 4
2023-02-22T03:55:55,063 WARN [runner.ScriptBindingsManager]: 24 * 5 = 120
2023-02-22T03:55:55,063 WARN [runner.ScriptBindingsManager]: The running total is 24 and the current item from the range is 5

The first result is simply the injected value 1 times the first value in the range, which is also one.  The next result is the current value of the running total, 1, times the current value in the range, 2.  It iterates through the values in the range like so, keeping a running tally of the results.

I suppose if you wanted to sum up the total of a list of integers, you could find a way to make this useful.  Me, I’ll stick to my trusty += operations.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>