Skip to content

Instantly share code, notes, and snippets.

Last active Mar 4, 2016
What would you like to do?
import groovy.transform.*
Map<String, ?> makeMap() {
def map = [string: "string"]
map.number = 1
return map
def map = makeMap()
map.each { println it.value.getClass().name }
Copy link

robfletcher commented Mar 4, 2016

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"

Copy link

dmahapatro commented Mar 4, 2016

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] } ]

Copy link

dmahapatro commented Mar 4, 2016

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