In java, a method call that I expect to return a value that must be captured is not throwing a compile error. Why?

In java, a method call that I expect to return a value that must be captured is not throwing a compile error. Why?

It is not a language requirement that the value returned from a method be used.

This situation happens routinely and frequently, eg:

Set<Integer> set = new HashSet<Integer>();
set.add(1); // returned boolean ignored

Set#add() returns a boolean value indicating if the set was changed as a result of calling it with the given parameter (returns false if the set already contained the value), but most of the time the returned value is ignored as in the snippet.

You dont have to store a return value in a variable. Just because its returned doesnt mean you have to keep it around.

In java, a method call that I expect to return a value that must be captured is not throwing a compile error. Why?

The compiler is not erroring because everything you wrote is legal java.

You did not say in your question where specifically you thought the compiler should error at. Without knowing more, I can assume you think that just because a method has a return type that the caller of that method must assign it to something. Java does not enforce that at all – a client of a class may call a method and completely ignore its return value legally.

Leave a Reply

Your email address will not be published. Required fields are marked *