Milan
Milan

Reputation: 1750

Groovy: Constructor hash collision

I have the following groovy code:

def    script
String credentials_id
String repository_path
String relative_directory
String repository_url

CredentialsWrapper(script, credentials_id, repository_name, repository_group, relative_directory=null) {
    this(script, credentials_id, '[email protected]:' + repository_group +'/' + repository_name + '.git', relative_directory);             
}

CredentialsWrapper(script, credentials_id, repository_url, relative_directory=null) {

    this.script         = script;
    this.credentials_id = credentials_id;
    this.repository_url = repository_url;

    if (null == relative_directory) {

        int lastSeparatorIndex  = repository_url.lastIndexOf("/");
        int indexOfExt          = repository_url.indexOf(".git"); 
        this.relative_directory = repository_url.substring(lastSeparatorIndex+1, indexOfExt);
    }
}

Jenkins gives me the following:

Unable to compile class com.foo.CredentialsWrapper due to hash collision in constructors @ line 30, column 7.

I do not understand why, the constructors are different, they do not have the same number of arguments.

Also, "script" is an instance from "WorkflowScript", but I do not know what I should import to access this class, which would allow me to declare script explicitly instead of using "def"

Any idea ?

Upvotes: 1

Views: 202

Answers (1)

andi
andi

Reputation: 361

When you call the Constructor with four parameters, would you like to call the first or the second one?

If you write an constructor/method with default values, groovy will actually generate two or more versions. So

Test(String x, String y ="test")

will result in

Test(String x, String y) {...}

and

Test(String x) {new Test(x, "test")}

So your code would like to compile to 4 constructors, but it contains the constructor with the signature CredentialsWrapper(def, def, def, def) two times. If I understand your code correctly, you can omit one or both of the =null. The result will be the same, but you will get only two or three signatures. Then you can choose between both versions by calling calling them with the right parameter count.

Upvotes: 2

Related Questions