Search code examples
javaconditional-operatoroverloadingvariable-types

How can I force Java to accept a conditional type for one of the parameters of a method call?


This question is hard to phrase, so I'm going to have to use some code samples. Basically, I have an (overloaded) method that takes 3 parameters, the last of which I overloaded. As in, sometimes the last parameter is a String, sometimes it's a double, etc. I want to call this method using a ternary conditional expression as the last parameter, so that depending on a certain value, it will pass either a double or a String. Here's an example...

Overloaded method headers:

writeToCell(int rowIndex, int colIndex, double value)

writeToCell(int rowIndex, int colIndex, String value)

What I'm trying to do:

writeToCell(2, 4, myValue != null ? someDouble : someString);

This, however, causes a compilation error:

The method writeToCell(int, int, double) in the type MyType is not applicable 
for the arguments (int, int, Object&Comparable<?>&Serializable)

It seems that Java isn't "smart enough" (or just doesn't have the functionality built in on purpose) to realize that either option has a method that supports it. My question is - is there any way to do this? I know I can sort of simulate it by passing in the double as a String (e.g. writeToCell(2, 4, myValue != null ? someDouble.toString() : someString);), but the method needs to receive it as a double data type.

Logic tells me that there's no way to force Java to accept this statement... But it's worth a try, as it will result in a lot clearer code for me. Anyone know of a way to do this...?


Solution

  • Thanks everyone for all your suggestions and explanations.

    A coworker of mine took a look at my code and suggested a solution that I implemented. I inserted the following code into the beginning of my double method:

    if(value == null){
       writeToCell(rowIndex, colIndex, someString)
    }
    else{
       ...method body... 
    }
    

    I know that this implementation might not always be the best idea, but since I almost always need to check for null when passing a double value to this method, it makes the most sense in this situation. This way I don't have to repeat the check code (if / ternary statement) each time, and my method calls are much cleaner.