Skip to content

Instantly share code, notes, and snippets.

@robfletcher
Last active March 4, 2016 02:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robfletcher/d9207087ca9665bfa0da to your computer and use it in GitHub Desktop.
Save robfletcher/d9207087ca9665bfa0da to your computer and use it in GitHub Desktop.
import groovy.transform.*
@CompileStatic
Map<String, ?> makeMap() {
def map = [string: "string"]
map.number = 1
return map
}
def map = makeMap()
map.each { println it.value.getClass().name }
@robfletcher
Copy link
Author

This surprised me – the method returns a Map<String, String> having seemingly inferred the value type from the initial assignment. When the integer value is added it gets coerced to String. This happens with any type (I stumbled on it while adding a List<Map<String, String>> to a map in a similar way).

Things to try:

  1. Remove @CompileStatic
  2. Replace def with Map<String, ?> on line 5
  3. Replace def with Map<String, Object> on line 5
  4. Replace the initial assignment with [:]
  5. Reverse the order of adding stuff to the map
  6. Add as Map<String, ?> at the end of line 5
  7. Repeat 4 but follow with map.string = "string"

@dmahapatro
Copy link

This is weird. I have also noticed it works for initialization like below:

def map = [string: 'string', numbers: [1, 2, 3, 4].collect { [n: it] } ]

@dmahapatro
Copy link

println map.number.getClass().name

immediately after line 6 prints as String.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment