Void et al.

Java Multithreading
Level 9 , Lesson 10
Available

"Hi, Amigo! I've got another small and interesting topic for you. The Void type."

"And why would you need such a type? I mean, I understand void: it's to bring functions and procedures into alignment. We don't have procedures, but we have functions that return void (nothing)."

"Yep, but do you remember that Ellie recently told you about the Callable interface?"

"Yes."

"And do you also remember what you need to pass as a type argument?"

"Yes, the type of the return value:"

Example of a task that does nothing:
class EmptyJob implements Callable
{
 public String call() throws Exception
 {
  return null;
 }
}

"Right. And what if you want the call method to return an int? What then?"

"Now I know that there's autoboxing for this. I would just pass an Integer, and everything will go like clockwork:"

Example of a task that does nothing:
class EmptyJob implements Callable
{
 public Integer call() throws Exception
 {
  return null;
 }
}

"Excellent. And what if the method should return nothing?"

"I get your point. Then we use Void as the counterpart of void?"

"Yep."

"Wouldn't it be easier to just make the return value an Object and then return null?"

"Sometimes, but not always."

"You know you really meant to return void here when you wrote Object, but another programmer might not know this and will think why you're returning null."

"Or the code calling the method will expect a return value."

"But when you write Void, everyone immediately understands that this is a wrapper for void, even though you still have to return null."

Example of a task that does nothing:
class EmptyJob implements Callable
{
 public Void call() throws Exception
 {
  return null;
 }
}

"Hmm. You're right. A method that always returns null raises questions. But the method declared as Void can do this without requiring further explanation."

"Code readability comes first. I like Java!"

"Great. I'm glad you like it. We're done for today."

Comments (2)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Mateusz Level 36, Wroclaw, Poland
29 February 2020
Ok, I saw the same code three times? I think: I drank too much vodka that day :)
WIDMO Level 25, Gdańsk, Poland Expert
29 July 2020
probably it was Vodka, starting with a capital V ;)