Apex Method Overloading is not working when called from LWC javascript Controller

apeximperativeapexlightning-web-components

Recently i have observed this weird behaviour and i am not sure is this expected behaviour or i am doing some kind of syntactical error.

I have two method with same name(suppose "methodOfClassA") in a apex class (suppose ClassA). The difference these methods have is number of parameters it accepts.

Now when i am invoking this two methods from lwc javascript controller at two different point of time(let's assume at two button click), only one method is getting invoked which has multiple parameter.

here is how my code looks like:
ApexClass :-

@AuraEnabled
public static string methodOfClassA(string param1){
  return param1;
}
@AuraEnabled
public static string methodOfClassA(string param1,String param2){
  String subString = param1+'-'+param2;
  return subString;
}

Javscript Controller-

invokeSingleParam() {
    methodName({param1:'parameter'})
        .then(resultReturned =>{
            console.log("param1 returned =>",resultReturned);
         })
        .catch(error =>{
            console.log("error ==> ",error.message);
        })
}

invokeSingleMultipleParam(){
    methodName({param1:'One Param',param2:'second Param'})
        .then(resultReturned =>{
            console.log("substring returned =>",resultReturned);
        })
        .catch(error =>{
            console.log("error ==> ",error.message);
        })        
}

here the screenshot of printed console.log

enter image description here

can anyone Please help me, why the polymorphism behavior of apex class is not working here?

Best Answer

This has nothing to do with polymorphism. Polymorphism deals with situations where you have multiple classes that share a common ancestor. What you're dealing with are called "overloaded methods." This is not supported with @AuraEnabled. Each method you want to call must have a unique name. This is because of how the underlying API is designed.

When calling one Apex method from another, the compiler selects the most appropriate overloaded methods based on the method signature (e.g. the count and type of parameters), but the JavaScript API cannot determine which method to use in real-time, so only one is called. If you reversed the order in the source code, you'd probably find that the one-parameter version is called instead, but there is no guarantee. You must use separate names for each version of the method if you want to call them from Aura or LWC.

Note that Aura has an additional restriction that the client-side controller and server-side Apex class cannot have methods by the same name, either, otherwise it is indeterminate which method will be called when using component.get("c.someMethod").