Type constraints of filter() too restrictive.

2007-09-26
2013-04-19
  • David Vallner

    David Vallner - 2007-09-26

    The signature of filter() should be changed to:
    <P> List<P> filter(Function1<Boolean, ? super P> p_filter, Collection<? extends P> p_coll)

    The Java compiler prefers to capture the type P from the signature of p_filter, not the desired result type, so for example the following will fail to compile, despite being typesafe:

    interface Furniture {
      boolean isWooden();
    }

    class Chair {
      private boolean wooden;

      public boolean isWooden() { return wooden; }

      public Chair(boolean wooden) { this.wooden = wooden; }

    }

    void test() {
      List<Chair> chairs = Arrays.asList(new Chair(true), new Chair(false));
      Function1<Boolean, Furniture> isWoodenFunc = new JdkStdReflect().instanceFunction(Furniture.class, "isWooden");
      List<Chair> woodenChairs = Functions.filter(isWoodenFunc, chairs); // Compiler complains here.
    }

    Otherwise, the library so far cut swathes through my LOC of stuff that was implementing the same without the reflection shortcuts.

    David Vallner

     
    • Fred Daoud

      Fred Daoud - 2007-09-28

      Hi David,

      Thanks for your message, I'll try to publish the fix ASAP. Nice one.
      I'll check the API to see if there are other places where this kind of change is needed; if you see any, please let me know.

      I'm glad the library is useful to you.
      Cheers,
      Frederic Daoud

       

Log in to post a comment.