This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes build function that return different types based on param Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "build function that return different types based on param " Watch "build function that return different types based on param " New topic
Author

build function that return different types based on param

Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
Hello all
I like to write simple java function that will return me different values some times String or Int or Boolean
based on given arg
some thing like :
if(arg==1){
return (int)foo;
}elseif(arg==2){
return (String)foo;

}elseif(arg==3){
return (boolean)foo;

}
What kind of function type I need to define my function?
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Why do you want to do that???


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
im getting Object[] array as arg then I
then in side this function I have another function that will cast me the elements from that array as I tell it for that I need this general java function
can it be done in java ?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
You won't be able to make those casts work. You can't cast an object reference to a primitive.

Could you describe the full problem and show the rest of the code?
Timothy Frey
Ranch Hand

Joined: Jul 22, 2006
Posts: 56
What you're looking for is not possible in Java (or any statically typed language I would think). The closest you can get would be to return something of type Object but of course you're already given a whole bunch of Objects that you're trying to cast in the first place.

If you feel that you must keep your current design, you can try the "instanceof" operator in a huge if-else if block to do the casting. However, this problem has BAD DESIGN written all over it. Any reason why it's an array of Objects instead of something more meaningful? Are you given any clues as to what order the objects come in?
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Timothy Frey:
What you're looking for is not possible in Java (or any statically typed language I would think).


And in a dynamically typed language, the casts wouldn't be necessary at all...

Meir, what would the clients of the method do with the returned value?
Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
ok im conversion some kind of in-house server script lang to jsp
in this lang I have function that called format that takes 2 args ;
Format.format("N",arg1) what it does is , first parameter is the type returned in this case "Number" , it can be also
Format.format("S",arg1) returned in this case "String" , and the second arg is the variable .

what I did ( its not perfect at all)
I made class called Format

public class Format {
public String format(String szFormat,int val){
String s = Integer.toString(val);
return s;
}
public String format(String szFormat,String val){
//int i = Integer.parseInt(val);
String i = val;
return i;
}
}

but as you can see I have problem when I have variable from type int that I what it to format it to int not string
or variable from type string and return it as int .
I hope I made my self clear im still looking for some way to do it �
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Instead of overloading the method names, give the two methods different names. Then they can return different types.
Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
Yeah I was thinking about it but I have something like 1000 pages to convert and I try to do minimum search and replace
I just need to know if there is some kind of trick to do it
Thanks
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
So those methods will be called from JSPs? What will typical JSP code look like?
Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
this is working fine from jsp with the class
<%
Format ft = new Format();

%>
<option value="<%= ft.format("S",szName) +"|"+ ft.format("S",szUser) %> >
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

In that case the JSP and scriptlet business is going to convert the result of those methods to Strings anyway. So having the methods all return String shouldn't be a problem.
Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
yeah but what if i have this case :
String szNum = "242";
int iVar = ft.format("N",szNum );

here i need it to return int based on "N"
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
It's not possible in a statically typed language like Java. You will need to use different methods based on the return type.
Meir Yan
Ranch Hand

Joined: Apr 27, 2006
Posts: 597
hello and thanks for the fast reply
maybe there is some trick or work around to this matter
basically what im looking for is some kind of factory pattern no?
can you please move this thread to the more advance java forum ?
thanks allot
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
No, there is no workaround.

The point is that the compiler statically checks the types at compile time. More specifically, in an assignment it checks that the compile time type of the right side value is assignment compatible to the left side.

In your last example, the compile time type of the left hand side was int. So the method you call on the right side of the assignment operator has to have a return type that is assignment compatible to int. There is no way to declare that method so that in other circumstances, given other arguments, it could return a String.

Well, in fact there is a way, if you use Java 5 and use Class as the first parameter instead of String - then you could use generics:

public <T> T format(Class<T> format,int val)

For that method, the compiler knows that

format(String.class, 42);

returns a String, but

format(Integer.class, 42);

returns an Integer. Together with auto-unboxing, the line

int i = format(Integer.class, 42);

becomes valid.

But is that really better than having a formatAsInteger method?
Steve Fahlbusch
Bartender

Joined: Sep 18, 2000
Posts: 557
    
    7

The trick here would be (if the coding was using constants as the first arg) would be to automatically change all occurances of 'format("N",' to 'formatN(' - same with string - might as well bit the bullet now and get rid of the problem once and for all.
Tom Sullivan
Ranch Hand

Joined: Dec 20, 2005
Posts: 72
I'm interested in this from a learning perpsective. Why don't you create test methods that will test the string for type? Then you could return an enum. Why would something like this not work:



Then you can create methods for each type you desire and pass the string to it to get the value which you know is the value you need. It sort of sounds like you already know what type you need though so what is the reason you would not create methods that return the type you need and just call those methods when appropriate?
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
You could use a parameterized type:

or a type with a parameterized method whose type is inferred by a parameter:

or a type with a parameterized method whose type is inferred by return value assignment:

They all have problems that need to be considered, but I'm betting you have a deeper underlying problem to derive a contradictory requirement such as the one that you have.


Tony Morris
Java Q&A (FAQ, Trivia)
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Tony Morris:
or a type with a parameterized method whose type is inferred by return value assignment:



So if I understand correctly, the compiler would now infer that for

int i = foo.get(p);

T is Integer?
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Ilja Preuss:

<hr></blockquote>

So if I understand correctly, the compiler would now infer that for

int i = foo.get(p);

T is Integer?

Correct. One of the consequences of this (a return type inferred generic method) is that you cannot look at the method invocation in isolation since 1.5 - you must also observe the return assignment to gather the full context of the method invocation.
Given the code:

...one cannot observe the method call (method()) in absolute isolation from the return type assignment. This is a little unintuitive and is one of the many (undocumented?) quirks on 1.5 - I actually gave a talk just recently on many of them.
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170


Thats as close as you will get. In 1.5 maybe autoboxing will help I'm not sure. If your converting the whole script to Java then it should not be an issue to use Integer rather than int.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Mr. C Lamont Gilbert:
Thats as close as you will get.


So you are saying that you don't see using generics as a helpful option?
Aaron Harp
Greenhorn

Joined: Jul 12, 2006
Posts: 8
Originally posted by Tom Sullivan:
I'm interested in this from a learning perpsective. Why don't you create test methods that will test the string for type? Then you could return an enum.


I'm very new to java so I'm interested in this as well. Would this approach not work? Could you not have a method that checks the type and then sends the passed data to the appropriate method to handle it?
 
Consider Paul's rocket mass heater.
 
subject: build function that return different types based on param
 
Similar Threads
final reference variables
build function that return different types based on param
is there any way pass arguments to class method without overloading ?
For Loop Doubt