ACMNexus / google-collections

Automatically exported from code.google.com/p/google-collections
Apache License 2.0
0 stars 0 forks source link

NullPointerException in Function.apply #244

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
com.google.common.base.Function
line 53

Function.apply has a @Nullable annotation on its parameter type:

T apply(@Nullable F from)

The annotation indicates that null may be passed as an argument to
apply without causing a NullPointerException, as in the following
method:

 private <T> void applyTest(Function<T,String> f, T o) {
  f.apply(o); // should never throw a NullPointerException
 }

However, the following unit test fails by throwing a NullPointerException:

 public void toStringApplyNull() {
  applyTest(Functions.ToStringFunction(), null);
 }

The problem is that the implementation of
com.google.common.base.Functions.ToStringFunction is inconsistent with
the annotation:

 public String apply(Object o) {
  return o.toString();
 }

This can be fixed in one of two ways.  The correct fix depends on the
intended specification of Function.apply:  can a client depend on null
being a legal argument to apply?

* If not, remove the @Nullable annotation of line 53 on Function.
* If so, change the implementation of ToStringFunction.apply to the following:

 public String apply(@Nullable Object o) {
  return (o == null) ? "null" : o.toString();
 }

The first option (removing the @Nullable) annotation is more useful to
clients of the Function interface, but it imposes restrictions on
implementations of the Function interface.  All current implementations
except for ToStringFunction satisfy those restrictions.

A patch for the relevant unit test is TestToStringNull.patch

A patch for fix #2 is ToStringFix.patch

Original issue reported on code.google.com by mala...@gmail.com on 18 Sep 2009 at 11:01

Attachments:

GoogleCodeExporter commented 8 years ago
See the @Nullable discussion in issue 247.

Original comment by limpbizkit on 19 Sep 2009 at 6:35