tag:blogger.com,1999:blog-1083890928935553699.post3298284924817118438..comments2023-04-02T08:51:54.059-04:00Comments on Rob's Musings: a groovy way to count number of linesRobby O'Connorhttp://www.blogger.com/profile/10437521195914796737noreply@blogger.comBlogger5125tag:blogger.com,1999:blog-1083890928935553699.post-47079101892111352742012-05-23T07:02:38.771-04:002012-05-23T07:02:38.771-04:00couldn't figure for a while why this wasn'...couldn't figure for a while why this wasn't working for me, then noticed the num++ (return current value then increment)<br /><br />changing it to ++num (increment then return) gave me the right count<br />num + 1 also works<br /><br />Something must have changed between 2008 and 21012 :D<br /><br /><br />println new File("names.txt").newReader().iterator().inject(0) { num, l -> num++ }<br /><br />OR<br /><br />println new File("names.txt").newReader().iterator().inject(0) { num, l -> num + 1 }<br /><br />I prefer the second alternative (num + 1) it's clearer that the closure variable isn't being modified itself but that the return is fed in to the next iteration.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-1083890928935553699.post-24325191516913146792008-04-10T05:11:00.000-04:002008-04-10T05:11:00.000-04:00Jim, AWESOME!Jim, AWESOME!Robby O'Connorhttps://www.blogger.com/profile/10437521195914796737noreply@blogger.comtag:blogger.com,1999:blog-1083890928935553699.post-60167381661408704172008-04-10T02:51:00.000-04:002008-04-10T02:51:00.000-04:00After opening a JIRA issue on this, I was greeting...After opening a JIRA issue on this, I was greeting by none other than Guillaume with this response for how to do it:<BR/><BR/>println new File("names.txt").newReader().iterator().inject(0) { num, l -> num++ }<BR/><BR/>And there you go, no more need to define a variable.Jim LoVerdehttps://www.blogger.com/profile/12557703151341682318noreply@blogger.comtag:blogger.com,1999:blog-1083890928935553699.post-25357694757098982032008-04-04T13:42:00.000-04:002008-04-04T13:42:00.000-04:00That's not a bad idea :-xThat's not a bad idea :-xRobby O'Connorhttps://www.blogger.com/profile/10437521195914796737noreply@blogger.comtag:blogger.com,1999:blog-1083890928935553699.post-72440815379106088952008-04-04T05:04:00.000-04:002008-04-04T05:04:00.000-04:00Yes, but wouldn't it have been nicer if they didn'...Yes, but wouldn't it have been nicer if they didn't deprecate the use of inject on File? Then you could do:<BR/><BR/>println new File("names.txt").inject(0) { num, l -> num++ }<BR/><BR/>Everything nice neat and tidy on a single line without needing to declare a variableJim LoVerdehttps://www.blogger.com/profile/12557703151341682318noreply@blogger.com