Sum*_*uma 5 functional-programming scala pipe-forward-operator
有时我会执行一系列计算,逐渐转换一些值,例如:
def complexComputation(input: String): String = {
val first = input.reverse
val second = first + first
val third = second * 3
third
}
Run Code Online (Sandbox Code Playgroud)
命名变量有时很麻烦,我想避免这样做。我为此使用的一种模式是使用链接值Option.map:
def complexComputation(input: String): String = {
Option(input)
.map(_.reverse)
.map(s => s + s)
.map(_ * 3)
.get
}
Run Code Online (Sandbox Code Playgroud)
使用Option/ get但是对我来说并不自然。还有其他通常的方法吗?
实际上,使用Scala 2.13是可能的。它将介绍 管道:
import scala.util.chaining._
input //"str"
.pipe(s => s.reverse) //"rts"
.pipe(s => s + s) //"rtsrts"
.pipe(s => s * 3) //"rtsrtsrtsrtsrtsrts"
Run Code Online (Sandbox Code Playgroud)
版本2.13.0-M1已经发布。如果您不想使用里程碑版本,也许考虑使用backport?