2

Does Apex support method return type overloading ?

I mean can I have a method in a class that return different type depending on it's Inputs ?

2

1 Answer 1

7

Yes, if the method signature is different you can have a different return type

In a class you can have

Integer add(Integer) 
String add(String) 

But you can't have

Integer add(Integer)
String add(Integer)

A working example :

public class myClass {

  public Integer add(Integer num){
    return null;
  }

  public String add(String str){
    return null;
  }

}
3
  • Typically the strategy is to use a more general type and cast it as the specific type, rather than arbitrarily changing the function parameters. A good example being Database.query(String query), which always returns a list<sObject>
    – martin
    Commented Mar 20, 2017 at 9:58
  • Yes, but I think that is more a JAVA way of thinking, if the method can return the specific type we need, why add a step of casting each time we invoke the method !
    – benahm
    Commented Mar 20, 2017 at 10:02
  • In case of Database.query the list of sObject types is not limited we can always create new types, but If we need to return a limited list of type example : Integer, String, Boolean better to go with my example rather returning an Object type and cast it each invocation....
    – benahm
    Commented Mar 20, 2017 at 10:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .