gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 12:53:46 25 4
gpt4 key购买 nike

我如何以简单的方式链接/组成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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com