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

前端 未结 6 1111
忘掉有多难
忘掉有多难 2020-12-07 12:12

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() {
    //..         


        
6条回答
  •  无人及你
    2020-12-07 12:40

    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 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.) It has other assorted uses along these lines, like if you want to parameterize a Callable.

    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".

提交回复
热议问题