GrailsInAction / graina2

Source code for the 2nd edition of Grails in Action
90 stars 91 forks source link

MEAP v13 ch05 Section 5.3.4 tagcloudMap throws RTE #72

Open danhyun opened 10 years ago

danhyun commented 10 years ago

I am using grails 2.3.4 and working my way through the v13 of book.

I came across the wonderful demonstration of withCriteria and projections.

In this snippet:

def tagList = Post.withCriteria {
    createAlias "tags", "t"

    user { eq "loginId", "phil" }

    projections {
        groupProperty "t.name"
        count "t.id"
    }
}

tagList is an array of arrays. When building the tagcloudMap, the code is listed as:

def tagcloudMap = tagList.collectEntries { pair -> pair }

However, this results in a run-time exception: image

I did some research as I am a groovy novice and it appears that collectEntries needs to have a map returned from the closure. Because the entries in tagList are arrays and not maps, I think this is causing the run-time exception.

I have tried this:

def tagcloudMap = tagList.collectEntries { [ (it[0]) : it[1] ] }

And it appears to be in working order:

image

pledbrook commented 10 years ago

Thanks for the feedback. The closure doesn't have to return a map, but if not, it must be a list. So an alternative fix is:

def tagcloudMap = tagList.collectEntries { pair -> pair as List }

Groovy normally allows you to use arrays and lists interchangeably, but not in this case.

danhyun commented 10 years ago

@pledbrook thanks for the quick response. It's very satisfying to see that there is a groovier solution than

[ (it[0]) : it[1] ]

I should really start working through the Groovy in Action MEAP.