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))
PS:有一个有用的库,叫做funKTionale,它有类似的扩展函数来组合函数 - forwardCompose或andThen,和compose。
推荐阅读
- json - 为 Azure 资源创建复制循环
- flutter - 如何使用 Getx 修复 Flutter 中的导航栏悬停问题
- r - 了解有关箱线图的 ggplot2 文档中的数字
- javascript - Nextjs 静态文件 CORS 问题 - 导致链接在版本 10.1.4 上中断
- jquery - Jquery表单验证和提交
- python - Discord.py 在不保存音频文件的情况下播放 Gtts
- rust - Go 接口和 Rust 特征,以及将函数从 Go 移植到 Rust
- azure-logic-apps - 如何获取 Microsoft 认知服务 API 的端点和密钥?
- nginx - 如何配置 nginx 以显示 .ipynb scipy 笔记本而不下载它们
- eigen - 将特征添加到 PlatformIO