如何像Groovy';s<&书信电报;及>&燃气轮机;操作员
如何以简单的方式在Kotlin中链接/组合函数,例如在Groovy中使用>>操作符? Groovy语法(请参阅):如何像Groovy';s<&书信电报;及>&燃气轮机;操作员,groovy,kotlin,Groovy,Kotlin,如何以简单的方式在Kotlin中链接/组合函数,例如在Groovy中使用>>操作符? Groovy语法(请参阅): def plus2={it+2} def times3={it*3} //构图 def times3plus2=plus2>plus2)(3) 如何在Kotlin中实现同样的功能?Kotlin语言中没有此类内置功能,但您可以在lambda上创建扩展函数来解决该问题: /** * Extension function joins two functions, using the
def plus2={it+2}
def times3={it*3}
//构图
def times3plus2=plus2>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)) }
}
注意:有一个有用的库,叫做,它有类似的扩展函数来编写函数-前向编写或然后编写,和编写相关?另见,&c。另见,来自过去的爆炸谢谢,看起来更多的人考虑过它,但Kotlin只是没有提供它(现在?)。在我的程序中扩展语言或创建泛型lib不是我的风格,因此我将坚持使用替代方法(使用中间变量或使用let关键字)
/**
* 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)) }
}
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))