Constructor cannot be applied to '(T)' error when using @CompileStatic and generic class

192 Views Asked by At

I'm trying to 'mend' some other code that I've been upgrading.

I've boiled it down to a simple example generic class and then the use of that class.

First, I declared a generic parameterized class like so

//generic class 
class WillsAgent<T> {

    public  WillsAgent(T data) {//do nothing with this }
}

Then a consuming class that tries to use this like so

@CompileStatic
public abstract class Test<T> {



    public WillsAgent<T> agent( T state) {
        final WillsAgent<T> safe = new WillsAgent<T> (state)
        return safe
    }
}

with the @CompileStatic declaration in play, the IDE shows a red squiggle under (state) passing the parameter to the constructor like this

screen shot

If I comment out the @CompileStatic declaration - the error disappears

If i hover over the squiggle (with @CompileStatic enabled) it shows this: Constructor 'WillsAgent' in 'groovyx.gpars.agent.WillsAgent<T>' cannot be applied to '(T)'

I can't figure out how to correct this, other than removing the @CompileStatic

Does anyone have any ideas why it's complaining this and what to do to fix it?

1

There are 1 best solutions below

0
On

Quick fix: replace the following line:

final WillsAgent<T> safe = new WillsAgent<T>(state)

with:

final WillsAgent<T> safe = new WillsAgent(state)

The issue with the first line might be caused by IntelliJ IDEA's Groovy plugin. I tried compiling new WillsAgent<T>(state) using groovyc and it didn't throw any error. Also, if you compile the class in the IDE, it also compiles with no error.

The good news is that no matter if you compile new WillsAgent<T>(state) or new WillsAgent(stage), the bytecode that is compiled from the Groovy code in both cases looks similar to this one:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package groovyx.gpars.agent;

import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;

public class Test<T> implements GroovyObject {
    public Test() {
        MetaClass var1 = this.$getStaticMetaClass();
        this.metaClass = var1;
    }

    public WillsAgent<T> agent(T state) {
        WillsAgent safe = new WillsAgent(state);
        return safe;
    }
}