Java 8 中高阶函数的作用域 Combinator Pattern 的 lambda 语法

Scope in higher order functions in Java 8 lambda syntax of Combinator Pattern

提问人:Simeon Leyzerzon 提问时间:2/19/2020 最后编辑:Simeon Leyzerzon 更新时间:2/19/2020 访问量:227

问:

我正在尝试理解以下示例方法中的语法:create

import java.math.BigDecimal;
import java.util.function.Consumer;
import java.util.function.Function;

@FunctionalInterface
interface Before<T, R> extends Function<Consumer<T>, Function<Function<T, R>, Function<T, R>>> {

    static <T, R> Before<T, R> create() {
        return before -> function -> argument -> {
            before.accept(argument);
            return function.apply(argument);
        };
    }

    static <T, R> Function<T, R> decorate(Consumer<T> before, Function<T, R> function) {
        return Before.<T, R>create().apply(before).apply(function);
    }
}

public class BeforeExample {

    void demo() {
        System.out.println("----------------------------------");
        System.out.println("Starting BEFORE combinator demo...");
        System.out.println("----------------------------------");

        Function<BigDecimal, String> addTax = this::addTax;

        Consumer<BigDecimal> before = this::before;

        Function<BigDecimal, String> addTaxDecorated = Before.decorate(before, addTax);

        BigDecimal argument = new BigDecimal("100");
        String result = addTaxDecorated.apply(argument);

        System.out.println("Done - Result is " + result);
        System.out.println();
    }

    private void before(BigDecimal argument) {
        System.out.println("BEFORE: Argument is " + argument);
    }

    private String addTax(BigDecimal amount) {
        System.out.println("Adding heavy taxes to our poor citizen...");
        return "$" + amount.multiply(new BigDecimal("1.22"));
    }
}

有人可以解释一下吗:

  • 块中发生了什么以及变量如何,并在不似乎被传递到 的签名中而变得已知,以及return before -> function -> argument -> {...}beforefunctionargumentcreate
  • 倍数意味着什么。->

谢谢。

Lambda Java-8 函数式编程 闭包

评论


答:

1赞 Naman 2/19/2020 #1

在 -> 函数 -> 参数 -> {...} 之前返回发生了什么 块以及之前的变量、函数和参数是如何为人所知的 似乎没有被传递进来

以下代码段可帮助您了解块和其中变量的用法:

static <T, R> Before<T, R> create() {
    return new Before<T, R>() {
        @Override
        public Function<Function<T, R>, Function<T, R>> apply(Consumer<T> before) {
            return new Function<Function<T, R>, Function<T, R>>() {
                @Override
                public Function<T, R> apply(Function<T, R> function) {
                    return new Function<T, R>() {
                        @Override
                        public R apply(T argument) {
                            before.accept(argument);
                            return function.apply(argument);
                        }
                    };
                }
            };
        }
    };
}

倍数意味着什么。->

每个函数接口的 lambda 表示组合起来表示方法的实现。create