首页 > 解决方案 > 如何像 Groovy 的 << 和 >> 运算符一样在 Kotlin 中进行组合

问题描述

如何以简单的方式在 Kotlin 中链接/组合函数,例如在 Groovy 中使用 >> 运算符?Groovy 语法(参见http://groovy-lang.org/closures.html):

def plus2  = { it + 2 }
def times3 = { it * 3 }

// composition
def times3plus2 = plus2 << times3
assert times3plus2(3) == 11
assert times3plus2(4) == plus2(times3(4))

// reverse composition
assert times3plus2(3) == (times3 >> plus2)(3)

如何在 Kotlin 中做同样的事情?

标签: kotlingroovycomposition

解决方案


Kotlin 语言中没有这样的内置功能,但您可以在 lambda 上创建扩展函数来解决该问题:

/**
 * Extension function joins two functions, using the result of the first function as parameter
 * of the second one.
 */
infix fun <P1, R1, R2> ((P1) -> R1).then(f: (R1) -> R2): (P1) -> R2 {
    return { p1: P1 -> f(this(p1)) }
}

infix fun <R1, R2> (() -> R1).then(f: (R1) -> R2): () -> R2 {
    return { f(this()) }
}

/**
 * Extension function is the exact opposite of `then`, using the result of the second function
 * as parameter of the first one.
 */
infix fun <P1, R, P2> ((P1) -> R).compose(f: (P2) -> P1): (P2) -> R {
    return { p1: P2 -> this(f(p1)) }
}

使用这些扩展函数,我们可以在 Kotlin 中编写类似于您的代码:

val plus2: (Int) -> Int  = { it + 2 }
val times3: (Int) -> Int = { it * 3 }

// composition
val times3plus2 = plus2 compose times3
assert(times3plus2(3) == 11)
assert(times3plus2(4) == plus2(times3(4)))

// reverse composition
assert(times3plus2(3) == (times3 then plus2)(3))

PS:有一个有用的库,叫做funKTionale,它有类似的扩展函数来组合函数 - forwardComposeandThen,和compose


推荐阅读