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
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:
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.
AFAIK there is no way to do this in Groovy