views:

76

answers:

1

What I am trying to do is define a list which asks for a specific type (List<Integer>). During the initialization of the class I put in a list of String I expect it to throw some runtime casting error. But it doesn't - it runs fine.

This is probably grails 101 stuff im sure but could someone explain why this works and also how I would force some type to be used in a list?

class Test {
    String name
    List<Integer> numbers
}

def myList = ['a','b','c']
Test myTest = new Test(name:'test', numbers:myList) 
myTest.numbers.each() { print " $it" }

Output:
a  b  c
+5  A: 

Even in Java, that code wouldn't throw any runtime errors, because there is no runtime type checking of generics. However, the equivalent Java code to this line would generate a compile-time error:

Test myTest = new Test(name:'test', numbers:myList) 

though it is possible to do the same thing in Java without compile-time errors using reflection and other trickery.

The short answer to why this doesn't generate a compile-time error in Groovy is because Groovy's compile-time type checks are a lot looser than Java's. Even if the generic type isn't checked by the Groovy compiler, it's still useful from the point of view of readability and documentation.

how I would force some type to be used in a list?

AFAIK there is no way to do this in Groovy

Don
i think it's possible in Groovy++ but i doubt if you can use Groovy++ with Grails
Olexandr
tim_yates
Thanks for all the replies. I looked at the generic section in the groovy docs (http://groovy.codehaus.org/Generics) which refers to support of generics at the source code level but thats about it.As Don says, its good for readability
Primus