tags:

views:

69

answers:

2

I've got the following code on a Controller

    def db = new Sql(dataSource)
    def rawLines = db.rows("SELECT name FROM LINES")
    def lines = []
    /*(db.rows returns the values as [NAME:value] */
    rawLines.each {
        lines.add(it.name)
    }
    /*Then, use lines */

I can't keep away the impression that there is probably some way to do this in a more elegant way, something similar to a list comprehension in Python:

lines = [ l.name for l in db.rows("SELECT name FROM LINES") ]

Having to declare an empty list and then populate it doesn't seem the best way of doing things... Is it possible to do something like this, or Groovy doesn't allow it?

A: 

Well, If you are using grails, why aren't you simply using the a model class together with the findAll method?
Using plain raw SQL should be done on exceptional cases.

gizmo
Yes, this is one of these cases ;-) The table is a view, so there are some problems defining the table as a domain.
Khelben
+3  A: 

Can't you just use the spread operator, and do:

lines = rawLines*.name

(see http://groovy.codehaus.org/Operators#Operators-SpreadOperator%28.%29)

tim_yates
That works! Thank you.
Khelben