• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java generics: Function returning Void or other value  RSS feed

 
Daniel Zuckermann
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I'm wondering if it is somehow possible to make a generic function that returns Void (the object) or an other value like a String or Integer.

Thanks for your input.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can do it without generics - just declare it to return Object.

You can have a return type that's a generic type parameter, but for that to be useful the return type has to be connected in some way to some other type - e.g. a type parameter for the class, or one of the arguments to the method. But you'd need to give more information about exactly what you're trying to do to see whether that's appropriate.
 
Daniel Zuckermann
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. I know that Void is a reference to void and therefore null can be returned as an object.

What I was trying to do is making Collable's call method return different types depending on what kind of value is given to the Callable constructor. In the call method a switch statement shall check a condition and then execute some code. Depending on the case, null or another value (String, Integer, Collection...) is returned.

I know that is possible, but in this case I could also implement Runnable and call run.

Maybe I have found out the answer by myself:
Callable<Void> is used to make sure that the function returns absolutely nothing, but any other parametrization like Callable<Number> implicitly allows to return null which is the "Void object".


 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Daniel Zuckermann wrote:What I was trying to do is making C[a]llable's call method return different types depending on what kind of value is given to the Callable constructor...

I suspect you're waaay overthinking this. If you create a Callable<String>, then its call() method will return a String, and I can't honestly see any earthly reason why you would want to create a Callable<Void>, since
(a) Any type can be substituted with null.
(b) The whole point of a Callable (as opposed to a Runnable) is to return a result. Surely you could create a Callable<Boolean> which simply returns a result to say whether it worked or not (or even just Boolean.TRUE)?

It sounds to me like you want some sort of "reflective-y catch-all Callable", and I doubt that you actually need it.

Winston
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!