I'm using @CompileStatic for the first time, and confused as to how Groovy's map constructors work in this situation.
@CompileStatic
class SomeClass {
Long id
String name
public static void main(String[] args) {
Map map = new HashMap()
map.put("id", 123L)
map.put("name", "test file")
SomeClass someClass1 = new SomeClass(map) // Does not work
SomeClass someClass2 = map as SomeClass // Works
}
}
Given the code above I see the following error when trying to compile
Groovyc: Target constructor for constructor call expression hasn't been set
If @CompileStatic is removed, both constructors work properly.
Can anyone explain why new SomeClass(map) does not compile with @CompileStatic? And a possible addition, why does map as SomeClass still work?
As the
CompileStaticdocumentation says:As a result, a constructor with a Map argument is searched in the static compilation to "resolve it at compile time", but it is not found and thereby there is a compilation error:
Adding such a constructor solves the issue with the
@CompileStaticannotation, since it is resolved at compile time:You can check
StaticCompilationVisitorif you want to dig deeper.Regarding the line
You are using there the
asType()method of Groovy's GDKjava.util.Map, so it is therefore solved at runtime even in static compilation: