Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

java - What do I return if the return type of a method is Void? (Not void!)

Due to the use of Generics in Java I ended up in having to implement a function having Void as return type:

public Void doSomething() {
    //...
}

and the compiler demands that I return something. For now I'm just returning null, but I'm wondering if that is good coding practice...

I'm asking about V?oid, not v?oid. The class Void, not the reserved keyword void.

I've also tried Void.class, void, Void.TYPE, new Void(), no return at all, but all that doesn't work at all. (For more or less obvious reasons) (See this answer for details)

  • So what am I supposed to return if the return type of a function is Void?
  • What's the general use of the Void class?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So what am I supposed to return if the return type of a function has to be Void?

Use return null. Void can't be instantiated and is merely a placeholder for the Class<T> type of void.

What's the point of Void?

As noted above, it's a placeholder. Void is what you'll get back if you, for example, use reflection to look at a method with a return type of void. (Technically, you'll get back Class<Void>.) It has other assorted uses along these lines, like if you want to parameterize a Callable<T>.

Due to the use of generics in Java I ended up in having to implement this function

I'd say that something may be funky with your API if you needed to implement a method with this signature. Consider carefully whether there's a better way to do what you want (perhaps you can provide more details in a different, follow-up question?). I'm a little suspicious, since this only came up "due to the use of generics".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...