groovy - 像Groovy的<<和>>运算符一样如何在Kotlin中进行合成

标签 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中做同样的事情?

最佳答案

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))

P.S .:有一个有用的库,称为funKTionale,它具有与扩展功能相似的扩展功能- forwardCompose 和然后,以及组成

关于groovy - 像Groovy的<<和>>运算符一样如何在Kotlin中进行合成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53969329/

相关文章:

android - Jetpack 中的 map compose

android - Kotlin嵌套协程启动不会触发吗?

java - 如何解决 Groovy 与 Apache Common Logging 的冲突?

android - 注入(inject)到 Hilt 未实例化的任意 Logic 类中

java - Protobuf配置Intellij Idea Plugin Gradle-kotlin-dsl kotlin

file - 常规/ Jenkins : rename file

kotlin - 让 Kotlin 在将灵活/平台类型分配给非空类型时发出警告?

java - 用于 sonarqube 配置的 Jenkins groovy 初始化脚本

grails - 为什么此源代码在Grails 1.3.7中不起作用?

java - 我可以在多大程度上依赖 Java 的垃圾收集(Groovy)?