Partial function application in Java 8

后端 未结 1 735
野趣味
野趣味 2021-01-07 23:57

I want to partially apply a legacy method to some arguments using Java 8\'s newly introduced function objects.

Here is the method in question:

/**
 * A         


        
1条回答
  •  一生所求
    2021-01-08 00:36

    This achieves what I wanted to do:

    /*
     * Pass two arguments. The created function accepts a String and
     * returns a StringBuilder
     */
    Function addEllipsis = appendToMe -> appendChar(
            '.', 3, appendToMe);
    /*
     * Pass one argument. This creates a function that takes another two
     * arguments and returns a StringBuilder
     */
    BiFunction addBangs = (appendToMe,
            times) -> appendChar('!', times, appendToMe);
    
    // Create a function by passing one argument to another function
    Function addOneBang = appendToMe -> addBangs
            .apply(appendToMe, 1);
    
    StringBuilder res1 = addBangs.apply("Java has gone functional", 2);
    StringBuilder res2 = addOneBang.apply("Lambdas are sweet");
    StringBuilder res3 = addEllipsis.apply("To be continued");
    

    For a list of all of Java's predefined varieties of the function object have a look here.

    Edit:

    If you have a method with a lot of arguments, you can write your own kind of function:

    /**
     * Represents a function that accepts three arguments and produces a result.
     * This is the three-arity specialization of {@link Function}.
     *
     * @param 
     *            the type of the first argument to the function
     * @param 
     *            the type of the second argument to the function
     * @param 
     *            the type of the third argument to the function
     * @param 
     *            the type of the result of the function
     *
     * @see Function
     */
    @FunctionalInterface
    public interface TriFunction {
    
        R apply(T t, U u, V v);
    }
    

    Method accepting many arguments; you want to provide some of them:

    private static boolean manyArgs(String str, int i, double d, float f) {
        return true;
    }
    

    Here is how you use your custom function object:

    /*
    * Pass one of the arguments. This creates a function accepting three
    * arguments.
    */
    TriFunction partiallyApplied = (i, d, f) ->
                                                               manyArgs("", i, d, f);
    
    /*
    * Provide the rest of the arguments.
    */
    boolean res4 = partiallyApplied.apply(2, 3.0, 4.0F);
    System.out.println("No time for ceremonies: " + res4);
    

    0 讨论(0)
提交回复
热议问题