We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Same function, different return
Page Index Toggle Pages: 1
Same function, different return? (Read 488 times)
Same function, different return?
Oct 23rd, 2005, 12:53pm
 
I know you can make a function which has the same name, but different input value:
Code:

void setVal(int val) // int
{
intValue = val;
}
void setVal(float val) // float
{
floatValue = val;
}


But i can't seem to do that with return values..
Does anybody know if there any workarounds?

Code:

int getVal() // int
{
return intValue;
}
float getVal() // float
{
return floatValue;
}


seltar
Re: Same function, different return?
Reply #1 - Oct 23rd, 2005, 5:37pm
 
In the first chunk of code you are overloading the method for the different arguments. In the second chunk of code there is not way to determine which method is to be called and so you need to over load the return method arguments.

For instance you can try:
Code:

int getVal(int i){
return intVal;
}

float getVal(float f){
return floatVal;
}


which you would then call by placing a random int or float val in the method arguments:
Code:

intValue = getVal(0);
floatValue = getVal(0f);


The only issue about doing it this way is that it then becomes a pain to keep track of which value you are calling at any given time. In java there is a degree of auto casting and so you may end up with problems when you compile. It's far more common to have different methods to call the different values. For instance:
Code:
 int getIntVal(){
return intValue;
}
float getFloatVal(){
return floatValue;
}
Page Index Toggle Pages: 1