This always forces us to return a single parameter in case I need to return multiple, say a List and a String. This restriction is not there in function arguments.
views:
373answers:
7This problem is what functional languages such as F#, haskell etc. attempt to address. The problem is that in hardware, a function's return value was originally returned via a CPU register, so you could only return a single value. C syntax passed on this legacy and C++ (and C#, Java) also inherited this.
Hi Techmaddy,
In fact, some languages do what you exactly want. For example Python, look at this code. It returns 2 values: 1 string and another int.
>>> def myFunc():
... string_val = "techmaddy"
... int_val = 10
... return string_val, int_val
...
>>>
>>> s, i = myFunc()
>>>
>>> print s
techmaddy
>>>
>>> print i
10
I hope it would help.
PS: Under the covers, I guess Python is boxing it in a list and un-boxing it. I don't know Python that well to tell you what exactly it does.
or, return Object[] from your method, and do
return new Object[] { list, string};
If you need more parameterized return types, you could create Pair<X,Y> classes, or Triplet<Z,Y,Z> and return those.
If you need to do this frequently enough, then create a class just to hold the result and return that instead.
This also allows you to DOCUMENT what your function returns in the same way that the parameters are documented.
On way to handle complex return behaviour is to pass an interface which the method calls. e.g.
public interface Results<R> {
public void processing(String stage);
public void success(String mesg, R result);
public void successes(String mesg, List<R> result);
public void thrown(Throwable t);
}
public void process(Results<R> results, String text, List<String> data);
Javascript, fortunately for you, is a dynamic language. This means you can construct any kind of object you want and return it. This effectively meets your requirement of having a "parameterized" return value, albeit in a rather un-typesafe way.
For example:
function stuff() {
return {
"foo": "a",
"bar": "b"
}
}
var theStuff = stuff();
alert(theStuff.foo + theStuff.bar); // should output "ab"