Groovy map and Java map on Generics

groovy, java

Solution

This forum post talks about Groovy ignoring generics, specifically:

Groovy is a dynamically typed language, but you can statically declare the types of variables. Generics on the JVM are erased at compile time and only the raw type is available to the VM (this is true both for groovy and Java). In Java, there is compile time checking to ensure that you don't stuff an int into a list of strings. But, Groovy does not check types at compile time.

So, this means that the type parameter is not checked at compile time and not available at runtime.

Problem

I am new to Groovy, and I have a question regarding to the use of map: I know I can do: `def map = [key:"value"]` But what does it mean if I do this: `Map<String, String> map = ["1":1, "2":"2"]` This code compiles, but the map is not really a String->String map: `map.each({println it.key + ":" + it.value + "[" + it.value.class + "]"})` It prints: 1:1[class java.lang.Integer] 2:2[class java.lang.String] Can anyone helps me to understand how come a map explicitly typed with String->String can be assigned to a map object that contains String->Integer? Thank you! === Update === Thanks for the link provided by @GrailsGuy, if I am using @TypeChecked for the above code wrapped in a method, it will throw an error: `[Static type checking] - Incompatible generic argument types. Cannot assign java.util.Map <java.lang.String, java.io.Serializable> to: java.util.Map <String, String>` The explanation makes perfect sense now.

Original source

Related problems