函数复合

    1. //f(g(x)) m(x) = f(g(x))
    2. val add5 = {i: Int -> i + 5} // g(x)
    3. val multiplyBy2 = {i : Int -> i * 2} // f(x)
    4. fun main(args: Array<String>) {
    5. println(multiplyBy2(add5(8))) // (5 + 8) * 2
    6. val add5AndMultiplyBy2 = add5 andThen multiplyBy2
    7. val add5ComposeMultiplyBy2 = add5 compose multiplyBy2
    8. // P1 = 8; P2:add5的返回值
    9. println(add5AndMultiplyBy2(8)) // m(x) = f(g(x))
    10. println(add5ComposeMultiplyBy2(8)) // m(x) = g(f(x))
    11. }
    12. // infix 中缀表达式,Function1一个参数
    13. // Function1<P1, P2>.andThen()扩展方法,P1参数类型,P2返回值类型
    14. infix fun <P1, P2, R> Function1<P1, P2>.andThen(function: Function1<P2, R>): Function1<P1,R>{
    15. return fun(p1: P1): R{
    16. return function.invoke(this.invoke(p1))
    17. }
    18. }
    19. infix fun <P1,P2, R> Function1<P2, R>.compose(function: Function1<P1, P2>): Function1<P1, R>{
    20. return fun(p1: P1): R{
    21. return this.invoke(function.invoke(p1))
    22. }
    23. }