So lets say we need to define a function for sum of two numbers.
We would say:
public int add(int a,int b){
return a + b;
}
Here we are very sure that we will be returning a value of type integer. but in cases we may want to return a integer and a boolean or a string.
For example say a very common function in String Manipulation indexOf the function returns the index of matching substring.
int indexOf(String str)
The return type is integer. So to find “Fox” index in “One Sharp Fox” you will write.
“One Sharp Fox”.indexOf(“Fox”); and will get 10 index.
But what if the match is not found. In these cases you might want to return “No Match Found” or false. But you cannot because the return type is an integer. And therefore you will have to return a number and in this case it is “-1”.
and your no found comparision goes like
if(“One Sharp Fox”.indexOf(“Lion”) == -1 )
In Case of loosely typed languages we do not have this restriction and we can have more then one type in return.
I was working through one particular bug in our code where we have used a php function
array_search()
Now php being a loosely typed language can have more than one return type.
Array_search function returns the Key of the Search String in the array in case the match is found. But in case the match is not found it will return false instead of -1 as we have seen in case of java code example.
So for example if we have an array storing car brands.
$cars=array(“Saab”,”Volvo”,”BMW”,”Toyota”);
and if we do
array_search(“BMW”,$cars);