[SalesForce] Ambiguous method signature on NULL value

I know that all primitive types are objects and can be null in Apex

But is there a way to handle the null value when doing polymorphism ?

public class myClass{
    public myClass(String name){
        // handle input
    }

    public myClass(Integer num){
        // handle input
    }
}

new myClass(null);

I am getting the error below when trying to instantiate my class with a null value

Error on SFDevConsole

Best Answer

The compiler cannot figure out which method to call here in the anonymous window because you are calling with 'null' explicitly vs having a variable type which it can use to figure out what you want. So, for example this code would work just fine:

String test = null;
new myClass(test);

Or, you could do:

new myClass((String)null);

In both cases we are providing the compiler with the information it needs to figure out which method to call.