how.wtf

Invalid constructor name error in Apex

· Thomas Taylor

When deploying apex classes, a user may run into an odd error: Error: Compile Error: Invalid constructor name.

How to solve Invalid constructor name

Upon initial inspection, this error may be misleading. The class in question contains a working constructor or a new method was added that is not a constructor.

What gives?

Normally, this error indicates that a new method was added without adding the return type.

Example:

 1public class Foo {
 2
 3    private String bar;
 4
 5    public Foo(String bar) {
 6        this.bar = bar;
 7    }
 8
 9    public newMethod() {
10        // logic
11    }
12}

To fix this, simply add the return type to the method:

 1public class Foo {
 2
 3    private String bar;
 4
 5    public Foo(String bar) {
 6        this.bar = bar;
 7    }
 8
 9    // added void return type
10    public void newMethod() {
11        // logic
12    }
13}

Why does this error happen?

When a return type is omitted, the method is interpreted as a constructor because constructors do not contain return types.

#Apex  

Reply to this post by email ↪